我正在進行各種數學培訓計劃。我試圖實現一個for循環,以便用戶選擇的每個問題類型都會產生三個問題。如果用戶輸入正確的變量類型,這可以很好地工作。但是,如果用戶輸入錯誤的變量/變量類型,會發生奇怪的循環。這很難解釋,但如果你拿這些代碼,並嘗試給它一個錯誤的輸入,你很快就會看到。我不知道這可能是如何造成的,所以我想我會在這裏發佈。我已經註釋過,只有一種操作類型(加法)可用,僅用於調試目的。如果你輸入的東西不是程序期望的東西,你會看到。我很新的循環,並已在多個想法盡我所能,但我很短。謝謝!Loop Prints Else Statement Only
// Welcome
System.out.println("Hello and welcome to the Math Trainer!\n======================================");
System.out.println("Which math operation would you like to practice?");
// Print options to select from
System.out.println(" " + "[A]ddition");
System.out.println(" " +"[S]ubtraction");
System.out.println(" " + "[M]ultiplication");
System.out.println(" " + "[D]ivision");
System.out.println(" " + "[R]emainder");
// Ask for user input on which to choose
System.out.print("Enter your choice:" + " ");
String userLetter = stdin.nextLine();
// Calculate random values from seed and shift them within range
for(int count = 0; count < Config.NUMBER_OF_QUESTIONS; count++){
int ran1 = randGen.nextInt(Config.MAX_VALUE - Config.MIN_VALUE + 1);
int ran2 = randGen.nextInt(Config.MAX_VALUE - Config.MIN_VALUE + 1);
int ran1Shift = ran1 + Config.MIN_VALUE;
int ran2Shift = ran2 + Config.MIN_VALUE;
// Initialize different answers per operation
double additionAnswer = (double)ran1Shift + ran2Shift;
double subtractionAnswer = (double)ran1Shift - ran2Shift;
double multiplicationAnswer = (double)ran1Shift * ran2Shift;
double divisionAnswer = (double)ran1Shift/ran2Shift;
double remainderAnswer = (double)ran1Shift % ran2Shift;
// Prompt user with a question based upon random numbers and operation selection
// Presentation of addition problems
if(userLetter.equalsIgnoreCase("a")) {
System.out.print("What is the solution to the problem:" + " " + ran1Shift + " " + "+" + " " + ran2Shift + " = ");
if (stdin.hasNextDouble()) {
double userNum = stdin.nextDouble();
if (userNum == additionAnswer) {
System.out.println("That is correct!");
} else {
System.out.println("The correct solution is: " + additionAnswer + ".");
}
} else {
System.out.println("All solutions must be entered as decimal numbers.");
System.out.println("The correct solution is " + additionAnswer + ".");
}
}
else{
System.out.println("I'm sorry, I only understand choices of: A, S, M, D, or R!");
}
}
// Program exit
System.out.println("======================================");
System.out.println("Thank you for using the Math Trainer!");
}
}
請訪問[問題]頁面並[編輯]你的問題。我們不需要您的整個程序,只需要足夠的代碼來重新創建/理解問題。 – Spencer4134
當你在調試器中執行代碼時,你看到了什麼?哪一行代碼不符合您的預期? –
例如,如果輸入'z'而不是a,s,m,d或r,則程序將打印else語句3次。 – dj1121