0
두 번째 while 루프 while (numberOfTries < 2)
while 루프를 모두 취소하는 이유는 무엇입니까? 부정확 한 대답이 없으면 완벽하게 실행됩니다. 그러나 내가해야 할 4 가지 문제를 선택했다고 가정 해 봅시다. 그리고 나는 단지 첫 번째 문제에 불과합니다. while (numberOfTries < 2)
은 그 루프에서 빠져 나가야하기 때문에 프로그램은 틀린 두 번 말하고 나서 나에게 새로운 질문을 주어야한다. 그러나 그렇지 않습니다. 단지 모든 것을 끝냅니다. 나는 그것이 논리 문제가되어야한다는 것을 알고있다. 그래서 나는 무엇을 놓치고 있는가?왜 두 번째 while 루프는 두 while 루프를 모두 취소합니까?
import java.util.Random;
import java.util.Scanner;
public class Howthe {
public static void main(String[] args) {
// Open Scanner
Scanner scan = new Scanner(System.in);
// Ask user to choose number of problems to be made.
// Can only choose 4, 9, or 16
System.out.print("Choose a number of problems to be made (4, 9, 16): ");
int userChoiceOfProblems = scan.nextInt();
// Ask user to choose a number between 0 and 12
System.out.print("\nChoose a number between 0 and 12: ");
int userNumberBetween0and12 = scan.nextInt();
// Ask user to choose between add/sub or multiply/divide
System.out.println("\nChoose to:"
+ "\n0: add/sub your chosen number"
+ " and the randomly generated number: "
+ "\n1: multiply/divide your chosen number"
+ " and the randomly generated number: ");
int userArithmeticChoice = scan.nextInt();
int counter = 0;
String equationString;
int equationAnswer;
int numberOfAnswersRight = 0;
int numberOfTries = 0;
int userAnswerToQuestion;
if (userArithmeticChoice == 0){
while (counter < userChoiceOfProblems){
// Create random number to decide if add or sub used.
// add is equal to 0 and sub is equal to 1
Random rand = new Random();
int randomNumberBetween0and1 = rand.nextInt(1) + 0;
// Create random number that is multiplied by userNumberBetween0and12
int randomNumberBetween0and12 = rand.nextInt(12) + 0;
// Add and increase counter by 1
if (randomNumberBetween0and1 == 0){
// If numberOfTries is more than 2, then display answer.
while (numberOfTries < 2){
// Compute the right answer (addition).
equationAnswer = userNumberBetween0and12 + randomNumberBetween0and12;
// Produce string of equation, then display string (addition).
equationString = userNumberBetween0and12 + " + "
+ randomNumberBetween0and12;
System.out.println(equationString);
userAnswerToQuestion = scan.nextInt();
// If answer is right, increase numberOfAnswersRight.
if (userAnswerToQuestion == equationAnswer){
numberOfAnswersRight++;
System.out.println("Correct!");
break;
}
// If answer is wrong, continue loop and increase numberOfTries
else if (userAnswerToQuestion != equationAnswer){
numberOfTries++;
System.out.println("Incorrect");
}
} // end of while (numberOfTries < 2 && !quit)
counter++;
}
} System.out.println("Yout got " + numberOfAnswersRight + " problem(s) right!");
}
}
}
디버거에서 코드를 단계별로 실행하면 어떻게됩니까? –
솔직히 말해서, 저는 디버거를 사용한 적이 없습니다. – Trey
버그가 다시 발생하지 않는다면, 그것을 사용하는 법을 배워야합니다. 몇 시간이 아닌 몇 초 안에 문제를 해결하는 데 도움이되는 필수 도구입니다. –