如何在Java程序中创建一个计数器

/*This is a quiz program that will ask the user 10 questions. the user will answer * these questions and will be scored out of 10.*/ class Quiz { public static void main(String args[]) { // Instructions System.out.println("instructions"); System.out.println(" "); System.out .println("1. You wll be asked ten questions through out the quiz."); System.out .println("2. The first question will appear, you will have to answer that question for the next question to appear."); System.out .println("3. When you answer the last question you will be told your score."); System.out.println(" "); System.out.println("welcome to the basketball quiz."); // question 1 System.out.println(" "); System.out.println("Question 1. "); System.out.println("How tall is a basketball hoop? "); System.out.println("Type in Answer here:"); String Question1 = In.getString(); if (Question1.equalsIgnoreCase("10 Feet")) { System.out.println("Correct!"); } else { System.out.println("you got this questions wrong"); } // question 2 System.out.println(" "); System.out.println("Question 2. "); System.out.println("Who invented basketball? "); System.out.println("Type in Answer here:"); String Question2 = In.getString(); if (Question2.equalsIgnoreCase("James Naismith ")) { System.out.println("Correct!"); } else { System.out.println("you got this questions wrong"); } } } 

这是我写的程序。 我想制作一个计数器,用于记录每个问题的得分,然后在问题结束后将其显示给用户。 我试过用这个:

 int score=0; score=score+1; 

它不适用于第二个问题,但适用于第三个问题…它给了我一个错误。 还有其他方法可以做到这一点,还是我做错了什么?

看起来你走在正确的轨道上。 你需要在程序开始时声明一个socre变量。

 int score = 0; 

然后在每个打印出“正确”的问题中,你可以像这样增加分数:

  score++; 

在最后一个问题之后的程序结束时,您可以打印分数。

也许你应该发布你尝试时得到的错误。

更新:语法为score ++ NOT score = ++。 也就是说,取出=符号。

你做的是对的。 注意你的post评论; 您在发布的解决方案的最后需要分号。 此外,根据Java语言规范 ,最好使用所有小写字符命名变量:

 int score = 0; // question code score += 1; or score = score + 1; or score++; 

您需要将变量声明(int score = 0;)放在任何循环之外(if / else循环)。 最好将它放在main方法的第一行。

您的问题是可能的,因为您在给出答案的比较中,在名称“James Naismith”之后有一个空白字符。 要将其评估为true,用户必须使用确切的字符串“James Naismith”而不是“James Naismith”来回答

编辑:没关系,这不应该导致错误,但它仍然引起你的注意,因为它可能会影响程序的结果。