添加由空格分隔的字符串中的数字

问题描述:

我正在为课程编写一个程序,它会询问用户有多少学生在课堂上,以及他们参加了多少次考试。然后,使用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

从字符串添加数字,由空格分隔:

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