我写了一个程序,它从一个文件中读取数据,该文件包含学生的名字和每个学生不定数量的分数,我必须计算平均分数,但我似乎只能使程序为特定数量的分数工作。我怎么能做到这一点,因此它可以计算任何数量的平均分数。顺便说一下,该程序是用Java编写的。平均分数简化
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hw1;
import java.io.*;
import java.util.Scanner;
/**
*
* @author admin
*/
public class HW1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try
{
File file = new File("/Users/admin/Desktop/studentScores.in"); //reads form file
Scanner scan = new Scanner(file); //scans the file
while(scan.hasNextInt()) //while the scanner identifies integers
{
String name = scan.next();
String grade1 = scan.next();
String grade2 = scan.next();
String grade3 = scan.next();
String grade4 = scan.next();
String grade5 = scan.next();
String grade6 = scan.next();
String grade7 = scan.next();
String grade8 = scan.next();
String grade9 = scan.next();
String grade10 = scan.next();
int average = (Integer.parseInt(grade1) + Integer.parseInt(grade2) + Integer.parseInt(grade3) + Integer.parseInt(grade4) + Integer.parseInt(grade5) + Integer.parseInt(grade6) +Integer.parseInt(grade7) + Integer.parseInt(grade8) + Integer.parseInt(grade9) + Integer.parseInt(grade10))/10;
//decalre avergae variable and calculate it
System.out.println("Name:" + name + " Average:" + average); // print the name of the student and their average
}
}
catch(IOException e)
{
}
}
}
是否得分的数量每名学生不同,或者是它不变? –