gpt4 book ai didi

java - 平均分数简化

转载 作者:行者123 更新时间:2023-11-29 05:27:25 25 4
gpt4 key购买 nike

我写了一个程序,它从一个文件中读取数据,这个文件包含一个学生的名字和每个学生的不定分数,我必须计算平均分数,但我似乎只能让这个程序工作一个具体分数。我该怎么做才能计算出任意数量分数的平均值。顺便说一下,该程序是用 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)
{

}
}
}

最佳答案

此代码将根据需要循环多次。它会先读入名字,然后不断读入数字,直到看到另一个名字。

String next = scan.next();
while(scan.hasNext()) {
String name = next;
next = scan.next();
int total = 0;
int count = 1;
while(!next.matches("^[a-zA-Z]*$")) {
total += Integer.parseInt(next)
count++
next = scan.next();
}
int average = total/count;
System.out.println("Name: "+name+" Average: "+average);
}

关于java - 平均分数简化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22212703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com