所以,这个程序可以工作,可以运行,但我希望它是白痴证明!为此,我需要一些帮助.. 如果用户输入数字或什么都不输入,我不希望它转到下一行!
如果我按 Enter 键而不写任何内容,它仍然会转到下一行,并且变量 navn
最后完全为空。
如果我写一个数字,它也会做同样的事情。如果答案不满足提示,我该如何让它返回并再次尝试相同的 while 循环。
非常感谢:)
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.
}
}
最佳答案
请使用此代码:
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()) { //Only allow letters A-Z
navn = in.nextLine();
if(!navn.isEmpty() && navn.matches("[A-Za-z]+")){
System.out.println("Takk!"); //Says thank you if the user has entered letters
in.next();
break;
}
else{
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
in.next();
System.out.println("Skriv inn navn: ");
continue;
}
}
System.out.println("Skriv inn bosted: ");
while(in.hasNext()) { //Only allow letters A-Z
bosted = in.nextLine();
if(!bosted.isEmpty() && bosted.matches("[A-Za-z]+")){
System.out.println("Takk!"); //Says thank you if the user has entered letters
break;
}
else{
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
in.next();
System.out.println("Skriv inn bosted: ");
continue;
}
}
System.out.println("Hei, " + navn + "! Du er fra " + bosted + "."); //Prints out what the user has entered previously in a full sentence.
}
关于java - 如果参数不满足则重新启动while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39229548/