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

时间:2014-10-11 19:13:46

标签: java

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


    }

}

1 个答案:

答案 0 :(得分:0)

从字符串中添加以空格分隔的数字:

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