Java中测验的逻辑错误

问题描述 投票:-2回答:2

我的程序没有任何语法错误,但逻辑。输出应显示每个问题是否正确或不正确,并显示测验者获得的正确数量以及测验结束时的错误数量。

import java.util.Scanner;

public class SubtractionQuiz { 
  public static void main(String[] args) { 
    //Declare and initialize variables
    final int NUMBER_OF_QUESTIONS = 10;
    int correctCount = 0;
    int count = 0;
    int incorrect = 0;
    int temp;        
    Scanner input = new Scanner(System.in);

    while (count < NUMBER_OF_QUESTIONS) {
      // Declare and initialize two random numbers
      int number1 = (int)(Math.random()*10);
      int number2 = (int)(Math.random()*10);

      if (number1 < number2) { 
        temp = number1;
        number1 = number2;
        number2 = temp;              
        // Prompt the question 
        System.out.print("What is " + number1 + " - " + number2 + "? ");
        int answer = input.nextInt();             

        if (number1 - number2 == answer) 
            System.out.println("Correct!");
            correctCount++;                
         } 
         else 
            System.out.println("Incorrect");
            incorrect++;
            count++;                             
        }
        System.out.printf("You got %d correct and %d incorrect!", correctCount, incorrect);    
       }       
    }
java
2个回答
0
投票

至少,你的大括号看起来。没有开口支撑只有ifelse之后的第一行是条件的一部分。

 if (number1 - number2 == answer)   // <--- should there be a "{" here?
   System.out.println("Correct!");
   correctCount++;

     } 
     else // <--- need a  "{" here ?
        System.out.println("Incorrect");
        incorrect++;
        count++;


    }

建议清理缩进以保持一致,以便您可以更清楚地看到此问题。


0
投票

你还没有为if和else块添加开括号(包含多于1个语句),你也必须稍微重构代码。在此计划的评论中查找我的新增内容

import java.util.Scanner;

public class SubtractionQuiz { 
  public static void main(String[] args) { 
    //Declare and initialize variables
    final int NUMBER_OF_QUESTIONS = 10;
    int correctCount = 0;
    int count = 0;
    int incorrect = 0;
    int temp;

    Scanner input = new Scanner(System.in);

    while (count < NUMBER_OF_QUESTIONS) {
      // Declare and initialize two random numbers
      int number1 = (int)(Math.random()*10);
      int number2 = (int)(Math.random()*10);

      if (number1<number2) { 
        temp = number1;
        number1 = number2;
        number2 = temp;     

        // Prompt the question 
        System.out.print("What is " + number1 + " - " + number2 + "? ");
        int answer = input.nextInt();


        if (number1 - number2 == answer) { // adding an opening brace here
            System.out.println("Correct!");
            correctCount++;

        } else { // adding an opening brace here
            System.out.println("Incorrect");
            incorrect++;
        }
        count++; 
      }
    }
    System.out.printf("You got %d correct and %d incorrect!\n", correctCount, incorrect); //Moving this outside the while loop
 } //closing braces for main
} //closing braces for class
© www.soinside.com 2019 - 2024. All rights reserved.