计算Java无效条目

时间:2014-03-15 20:00:52

标签: java

我正在试图弄清楚如何不计入无效条目。 我需要输入5个分数,并且需要"得分数"到5,但我制作的代码只输入4"得分计数",包括无效条目。我不需要输入无效条目,也不知道如何排除无效条目被计为分数。

以下是代码。

import java.util.Scanner;

 public class TestScoreApp
 {
   public static void main(String[] args)
   {
       // display operational messages
       System.out.println("Please enter test scores that range from 0 to 100.");
       System.out.println("To end the program enter 999.");
       System.out.println();  // print a blank line

       Scanner sc = new Scanner(System.in);
       String choice = "y";

       // get a series of test scores from the user
       while (!choice.equalsIgnoreCase("n"))
       {
       // initialize variables
       int scoreTotal = 0;
       int scoreCount = 0;
       int testScore = 0;

    System.out.println("Enter the number of test score to be entered: ");
    int numberOfTestScores = sc.nextInt();

           for (int i = 1; i <= numberOfTestScores; i++)
           {
                // get the input from the user
                System.out.print("Enter score " + i + ": ");
                testScore = sc.nextInt();

                // accumulate score count and score total
                if (testScore <= 100)
                {
                     scoreCount = scoreCount + 1;
                     scoreTotal = scoreTotal + testScore;
                }
                else if (testScore != 999)
                      System.out.println("Invalid entry, not counted");
                      sc.nextLine();

            // display the score count, score total, and average score
            }
            double averageScore = scoreTotal / scoreCount;
            String message = "\n" +
                 "Score count:   " + scoreCount + "\n"
               + "Score total:   " + scoreTotal + "\n"
               + "Average score: " + averageScore + "\n";
            System.out.println(message);
            System.out.println();
            System.out.println("Enter more test scores? (y/n)");
            choice= sc.next();
                 }
         }
 }

以下是正在运行的文件的示例。

  

请输入0到100之间的测试分数。
结束   程序输入999.

输入测试分数   输入:5 5
输入得分1:66左边输入得分2:85   
输入得分3:99
输入得分4:79
输入得分5:457   
无效的条目,未计入

     

分数:4
分数:329
平均分:82.0
  

     

输入更多考试成绩? (Y / N)

1 个答案:

答案 0 :(得分:2)

如果循环迭代变量i是无效分数,则简单地减少它,因此您重新询问该分数。所以改变这个:

else if (testScore != 999)
    System.out.println("Invalid entry, not counted");

到此:

else if (testScore != 999) {
    System.out.println("Invalid entry, not counted");
    i--;
}