gpt4 book ai didi

java - 如何使用 Java 方法在循环内逐行处理输入文件?

转载 作者:行者123 更新时间:2023-12-01 19:45:40 29 4
gpt4 key购买 nike

我正在使用 Java 通过在循环内为每一行输入调用多个方法来处理文件。问题是方法只读取循环每次迭代的第一行输入。例如,输入:

Jones 90 90 90
Brown 80 80 80
Smith 70 70 70

应该输出:

Jones 90 A
Brown 80 B
Smith 70 C

但我最终得到的是:

Jones 90 A
Brown 90 A
Smith 90 A

是否可以在下面的代码中获取 studentAveragedefineGrade 方法来处理上面示例中的第二行和第三行输入,或者我是否需要重新考虑整个循环/方法结构?

import java.io.*;
import java.util.Scanner;

public class Lab07Part01
{
public static void main(String[] args) throws IOException
{
File infile = new File("Grades.txt");
Scanner myfile = new Scanner(infile);
Scanner counter = new Scanner(infile);

String studentName = "";
int testQty = 0;
int studentQty = -1;
double studentAvg = 0.0;
double classSum = 0.0;
double classAvg = 0.0;
char letterGrade = 'X';

while(counter.hasNextLine()) {
studentQty++;
counter.nextLine();
}

testQty = myfile.nextInt();

System.out.println("Name Average Letter Grade");
for(int i = 0; i < studentQty; i++) {
studentName = myfile.next();
studentAvg = studentAverage(testQty);
classAvg += studentAvg;
letterGrade = determineGrade(studentAvg);
System.out.println(studentName + " " + studentAvg + " " + letterGrade);
myfile.nextLine();
}

classAvg = overallAverage(studentQty, classSum);

System.out.println("The average test grade is: " + classAvg);

}

public static double studentAverage(int testQty) throws IOException
{
File infile = new File("Grades.txt");
Scanner scanavg = new Scanner(infile);
double studentSum = 0;

scanavg.nextLine();
scanavg.next();

for(int i = 1; i <= testQty; i++) {
studentSum += scanavg.nextDouble();
}

double studentAvg = studentSum / testQty;
return studentAvg;
}

public static char determineGrade(double studentAvg) throws IOException
{
char letterGrade = 'X';

if(studentAvg >= 90.0)
letterGrade = 'A';
else if(studentAvg >= 80.0)
letterGrade = 'B';
else if(studentAvg >= 70.0)
letterGrade = 'C';
else if(studentAvg >= 60.0)
letterGrade = 'D';
else if(studentAvg < 60.0)
letterGrade = 'F';

return letterGrade;
}

public static double overallAverage(int studentQty, double classSum) throws IOException
{
double classAvg = classSum / studentQty;
return classSum;
}
}

最佳答案

我会通过一次读取一整行来使用扫描仪。然后,我们可以通过一个逻辑步骤处理整行:

File infile = new File("Grades.txt");
Scanner myfile = new Scanner(infile);

while (myfile.hasNextLine()) {
String line = myfile.nextLine();
String[] parts = line.split("\\s+");
double average = 0.0d;
for (int i=1; i < parts.length; ++i) {
average += Double.parseDouble(parts[i]);
}
average /= parts.length - 1;
char letterGrade = determineGrade(average);

System.out.println(parts[0] + " " + average + " " + letterGrade);
}

关于java - 如何使用 Java 方法在循环内逐行处理输入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53493903/

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