プログラムの出力に問題があります。コンストラクターとしてクラス「GetInput」を開発しました。これは、入力についてさまざまな質問をするときに再利用できます。尋ねられる各質問は、クラス/コンストラクターに渡される最小数以上/最大数以下である必要があります。私が抱えている問題は、whileループが実行されると、最終的に正しい値を返す前に4回入力を要求することです。
表示時に計算したフラグを追加しました。最初は、入力が最初に追加された後に表示されます。次に2回目、次に4回目です。4回目は、1回の反復で到達させたいフラグ「終了」も表示します。最終的に値を正しく返す前に、なぜ4回ループするのですか?
よろしくお願いします。これはJavaを学ぶ2日目であり、これは私を狂気に駆り立てています。
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
}
}