我正在编写一个程序,该程序使用文件中的30个等级并计算最低,最高和平均等级。我无法弄清楚如何编写读取每个等级的循环语句并更新最低/最高等级,并在读取下一个等级之前将该值添加到总和中。
import java.io.*;
import java.util.*;
public class MidtermStat {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("grades.txt"));
int lowest = 50;
int highest = 50;
int sum = 0;
int i;
for (i = 0, i < 30, i++){
if (grade < lowest)
lowest = grade;
if (grade > highest)
highest = grade;
}
double average = sum / 30;
System.out.println("The average score is: " + average);
System.out.println("The highest score is: " + highest);
System.out.println("The lowest score is: " + lowest);
in.close();
}
}
谢谢你想出来:
import java.io.*;
import java.util.*;
public class MidtermStat {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new FileReader("grades.txt"));
int lowest = 50;
int highest = 50;
int sum = 0;
int i;
for (i = 0; i < 30; i++){
int grade = in.nextInt();
if (grade < lowest)
lowest = grade;
if (grade > highest)
highest = grade;
sum += grade;
}
double average = (sum / 30.0);
System.out.println("The average score is: " + (int)(average * 100) / 100.0);
System.out.println("The highest score is: " + highest);
System.out.println("The lowest score is: " + lowest);
in.close();
}
}
答案 0 :(得分:0)
我建议你去找缓冲读卡器。
例如
BufferedReader br = new BufferedReader(new FileReader("FilePath"))
上述语句会给你异常,你需要处理它。
while ((Line = br.readLine()) != null) {
// your statements..
}
快乐编码
答案 1 :(得分:0)
做这样的事情:
for(i=0;i<30;i++){
**float grade = in.nextFloat();**
if(grade<lowest) lowest = grade;
else if(grade>highest) highest = grade;
sum+=grade;
}
不要忘记更改用于“浮动”以获得精确度的每个“int”。
答案 2 :(得分:0)
如果您的文件包含浮动值
,请使用此选项while(b = in.hasNextFloat())
{
s = s1.nextFloat();
sum += s;
}
请记住,如果您从文件中获取输入,那么最好使用BufferdReader,因为文件保存在磁盘中,与我们的程序相比速度较慢。因此,最好在从文件读取时使用一些低级别流。 有关详细信息,请参阅:
http://docs.oracle.com/javase/tutorial/essential/io/buffers.html