因此,此程序可以运行,但它会运行,但我希望它是白痴证明!要做到这一点,我需要一些帮助。 如果用户输入了一个数字或者什么都没有,我不希望它进入下一行!如果参数未满足,则重新启动while循环
如果我按下输入而没有写任何东西,它仍会进入下一行,并且变量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.
}
}
。 – Berger
是的,谢谢! –
将所有内容放在while循环中只有当变量包含任何值时才退出while循环 –