我的程序输出有问题。我开发了“GetInput”类作为构造函数,在询问各种输入问题时可以重用它。提出的每个问题都需要等于或大于最小值/小于传递给类/构造函数的最大值。我遇到的问题是,当 while 循环运行时,它要求输入四次,然后才最终返回正确的值。
我添加了我在它们显示时计算出来的标志。第一次添加输入后的第一个显示。然后是第二次,然后是第四次。第四次它还显示我希望它在一次迭代中达到的标志“结束”。为什么在最终正确返回值之前循环了四次?
提前非常感谢。这只是我学习 Java 的第二天,这让我发疯了。
import java.util.Scanner; //Import the scanner class
public class main {
public static void main(String[] args) {
//Set variables to hold the entry cost for each category
int costAccChild = 2;
int costUnaccChild = 5;
int costAdult = 10;
int costSenior = 8;
int test = GetInput(0, 1, "Enter a group? (Yes=1/No=0)");
System.out.println(test);
System.out.println("the end");
}
static int GetInput(int min, int max, String request){
boolean inputValid = false; //Sets default value to variable for while loop
int userInput = 0; //Sets default variable for input return
while (inputValid == false) { //Loops until receives correct input
System.out.println(request); //Prints question asking for input
Scanner inputFromUser = new Scanner(System.in); //Ask user for input
System.out.print("First time"); //FLAG DISPLAYS AFTER FIRST SCANNER
if (inputFromUser.hasNextInt() == true){ //Check if input has an integer
System.out.print("Second Time"); //FLAG SHOWS AFTER SECOND SCANNER
if (inputFromUser.nextInt() >= min && inputFromUser.nextInt() <= max ){ //Check if input is valid
userInput = inputFromUser.nextInt();
inputValid= true;
System.out.print("Fourth time"); //FLAG WORKS FORTH TIME
}else{ //Input is not correct integer, give error message
System.out.println("Input is not valid");
}
}else{ //Input is not an integer at all, give error message
System.out.println("Input is not valid");
}
}
return userInput; //Returns valid input
}
}