因此,此程序可以運行,但它會運行,但我希望它是白癡證明!要做到這一點,我需要一些幫助。 如果用戶輸入了一個數字或者什麼都沒有,我不希望它進入下一行!如果參數未滿足,則重新啓動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循環 –