如果未满足参数,则重新启动while循环

时间:2016-08-30 13:58:10

标签: java

所以,这个程序有效,它运行,但我希望它是白痴证明!要做到这一点,我需要一些帮助.. 如果用户输入数字或根本没有输入任何数字,我不希望它转到下一行!

如果我按Enter键而没有写任何内容,它仍会转到下一行,变量navn在结尾处完全呈空。 如果我写一个数字,它也会做同样的事情。如果答案不符合提示,我如何让它返回并再次循环尝试。 非常感谢你:))

import java.util.Scanner;

class Metoder {

    public static void main(String[] args) {
        String bosted; //Variable
        String navn; //Variable

        Scanner in = new Scanner(System.in);

        System.out.println("Skriv inn navn: "); //What shows up when you first start the program

        while (!in.hasNext("[A-Za-z]+")) { //Only allow letters A-Z
            in.next();
            System.out.println("Tall horer ikke hjemme i navn, prøv igjen!"); //Prints, "numbers dont belong in names, try again" if what the user entered is a number

        }
        System.out.println("Takk!"); //Says thank you if the user has entered letters

        navn = in.nextLine(); //Proceeds to next line

        System.out.println("Skriv inn bosted: "); //Next line, where the user is supposed to enter where he/she lives
        while (!in.hasNext("[A-Za-z]+")) { //Excactly the same loop as above
            in.next();
            System.out.println("Tall hører ikke hjemme i stedsnavn, prøv igjen!");
        }
        System.out.println("Takk!");

        bosted = in.nextLine();

        System.out.println("Hei, " + navn + "! Du er fra " + bosted + "."); //Prints out what the user has entered previously in a full sentence.

    }
}

2 个答案:

答案 0 :(得分:1)

请使用此代码:

(x,y,z)

答案 1 :(得分:0)

您可以使用continue关键字重新启动循环。

while(!in.hasNext("[A-Za-z]+")) {
    try {
        String s = in.nextLine();
        if(s.isEmpty() || s.matches("^-?\\d+$")){
            throw new Exception("empty string or number detected");
        }
    } catch (Exception e){
        continue;
    }
}

if条件下,我们检查输入的字符串是否为空或是整数,并且我们可以抛出一个异常,这将导致while循环继续请求输入,直到条件失败(即通过我们的检验)。