2014-10-11 93 views
-2

我正在爲課程編寫一個程序,它會詢問用戶有多少學生在課堂上,以及他們參加了多少次考試。然後,使用for循環,它會根據您之前輸入的內容詢問每個學生的姓名和考試分數,一旦您輸入了該分數,就會得到他們的平均考試分數和其他一些內容。我遇到的問題是我無法弄清楚如何取得測試分數的平均值。我無法讓我的程序讀取用戶輸入的測試分數,然後取平均值。感謝您提前提供任何幫助。添加由空格分隔的字符串中的數字

import java.util.Scanner; 

public class GradeCalculator { 
    public static void main(String[] args){ 
     //Define Variables 
     int Students; 
     int Exams; 
     int Sum = 0; 
     int ExamAverage = 0; 
     String ExamScores; 
     String StudentName; 



     //Create Scanner 
     Scanner s = new Scanner(System.in); 

     //Print the First Block 
     System.out.println("Welcome to GradeCalculator!"); 
     System.out.println(""); 
     System.out.println("Please enter the number of students: "); 
     Students = s.nextInt(); 
     System.out.println("Please enter the number of exams: "); 
     Exams = s.nextInt(); 
     s.nextLine(); 
     System.out.println("- - - - - - - - - - - - - - - - - - - -"); 

     //For Loop 
     for (int i = 1; i<=Students; i++){ 
      System.out.println("Enter Student " + i + "'s name: "); 
      StudentName = s.nextLine(); 
      System.out.println("Enter exam scores: "); 
      ExamScores = s.nextLine(); 
      Sum+=Integer.parseInt(ExamScores); 
      ExamAverage = Sum/Exams; 
      System.out.println("Grade Statistics for " + StudentName); 
      System.out.println("\t Average: " + ExamAverage); 
      System.out.println("\t Letter Grade: "); 
      System.out.println("\t"+ StudentName + " gets a "); 
      System.out.println("- - - - - - - - - - - - - - - - - - - -"); 
     } 

     //Print the Last Block 
     System.out.println("Class Statistics:"); 
     System.out.println("\t Average: "); 
     System.out.println("\t Lowest: "); 
     System.out.println("\t Highest: "); 
     System.out.println(""); 
     System.out.println("Done, Good Bye!"); 


    } 

} 
+3

第一步:打破問題了。將問題分解爲其組成步驟,然後嘗試一次解決每個步驟。 – 2014-10-11 19:16:11

+0

在循環外移動ExamAverage。此外,你不增加考試。 – OldProgrammer 2014-10-11 19:17:29

回答

0

從字符串添加數字,由空格分隔:

String allNumbers = "12 34 67 34 56 78"; 
int total = 0; 
for(String str : allNumbers.split("\\s")){ 
    total+=Integer.parseInt(str); 
} 
+0

儘管如此,你如何爲所有學生做這項工作?例如,如果輸入3名學生,那麼該計劃會詢問您關於三名學生的信息,但平均值僅適用於第一名學生,而不是其他三名學生。 – bearmod 2014-10-11 20:17:08

相關問題