2013-02-06 64 views
1

有點新編程,我努力想弄明白的問題是這個。我的控制檯應用程序詢問用戶他們想要輸入多少測試分數來計算所有分數的平均值和總和。如果他們輸入3,則要求他們輸入3個測試分數,然後顯示所有分數的平均值和總數。然後詢問他們是否想繼續或結束該計劃,如果他們進入是的繼續,應該從頭開始。我的問題是,當我說是的時候,它並不清楚總分或總分數,它只是繼續前面的分數,而只是將新的分數加到這個分數上。把花括號放在正確的位置有問題嗎?

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 

      // initialize variables and create a Scanner object 
      int scoreTotal = 0; 
      int scoreCount = 0; 
      int testScore = 0; 
      Scanner sc = new Scanner(System.in); 
      String choice = "y"; 

      // get a series of test scores from the user 
      while (!choice.equalsIgnoreCase("n")) 
      { 
       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"); 


       } 
       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(); 
      } 



    // display the score count, score total, and average score 



    } 
} 

回答

1

只需將您的分數變量聲明while循環開始後:

// create a Scanner object 
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(); 

這樣,他們將在0每次初始化過程重新開始。

+0

Thanks感謝您的幫助 – babaysteps

1

while循環內部的第一條語句應該將scoreTotal和scoreCount設置爲0.

相關問題