我遇到了程序輸出的麻煩。我已經開發了類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