Java错误的用户输入循环,直到正确为止
我在验证程序时遇到问题。我试过使用While/Switch,但都一样。问题是,当用户输入错误的输入时(例如5),它会显示错误,然后让他们再次输入,但如果他们再次输入错误的数字,程序将无法验证。我肯定可以在其中一次又一次地复制代码,但应该有一种更简单的方法 我希望你能理解我想要实现的目标 我怎样才能使它成为一个连续的循环Java错误的用户输入循环,直到正确为止,java,validation,if-statement,input,Java,Validation,If Statement,Input,我在验证程序时遇到问题。我试过使用While/Switch,但都一样。问题是,当用户输入错误的输入时(例如5),它会显示错误,然后让他们再次输入,但如果他们再次输入错误的数字,程序将无法验证。我肯定可以在其中一次又一次地复制代码,但应该有一种更简单的方法 我希望你能理解我想要实现的目标 我怎样才能使它成为一个连续的循环 // Choosing the right room public static int rooms () { int room; // Creating a
// Choosing the right room
public static int rooms () {
int room;
// Creating a new keyboard input
Scanner scanner = new Scanner(System.in);
// Displaying a message on the screen
System.out.println("What room are you in? ");
// Input
room = scanner.nextInt();
if (room==1) {
roomOne();
} else if (room==2) {
roomTwo();
} else if (room==3) {
roomThree();
} else if (room==4) {
roomFour();
} else {
System.out.println("Wrong room number, please enter the room number.");
room = scanner.nextInt();
}
//System.out.println("Sorry but you entered the wrong room number " + room + " Enter the correct room number 1-4 ");
return room;
} // End Rooms
希望能有所帮助,不过您应该多读一些关于循环的内容
希望它能有所帮助,不过您应该多读一些关于循环的内容。以下是设置循环以进行输入清理的方法: 定义布尔值并指定真值或假值 使while循环在布尔值上运行 输入为干净时,将布尔值设置为true
以下是设置输入清理循环的方法: 定义布尔值并指定真值或假值 使while循环在布尔值上运行 输入为干净时,将布尔值设置为true
您正在寻找一个类似这样的while循环 我用的是做。。。而要执行该行至少一次 这些方法检查值,如果不正确,则打印消息。Return false将阻止代码退出循环并再次读取
{
// Creating a new keyboard input
Scanner scanner = new Scanner(System.in);
int room;
do {
// Displaying a message on the screen
System.out.println("What room are you in? ");
room = scanner.nextInt();
} while( !isValid(room) );
... //if else or switch
}
private boolean isValid(int room){
if(room > 4 || room < 1){
System.out.println("Try again ;)" );
return false;
} else return true;
}
这是一个快速的代码注释甚至测试。您正在寻找一个while循环,类似这样的东西 我用的是做。。。而要执行该行至少一次 这些方法检查值,如果不正确,则打印消息。Return false将阻止代码退出循环并再次读取
{
// Creating a new keyboard input
Scanner scanner = new Scanner(System.in);
int room;
do {
// Displaying a message on the screen
System.out.println("What room are you in? ");
room = scanner.nextInt();
} while( !isValid(room) );
... //if else or switch
}
private boolean isValid(int room){
if(room > 4 || room < 1){
System.out.println("Try again ;)" );
return false;
} else return true;
}
这是一个快速的代码注释甚至测试。您正在寻找方法和/或循环。您也可以使用whiletrue。您正在寻找方法和/或循环。您也可以使用whiletrue