我遇到了程序输出的麻烦。我已经开发了类GetInput作为构造函数,在询问各种输入问题时我可以重用。每个被问到的问题都需要等于或大于最小值/小于传递给类/构造函数的最大值。我遇到的问题是,while循环运行时,在最终返回正确的值之前,它要求输入四次。使用嵌套if语句在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
}
}
尝试使用Eclipse调试器和理解你的程序 – 2013-03-19 11:14:18