Java 从文件中读取成绩
我很难弄清楚我的编码有什么问题。它需要从文件中读取文本并打印平均值、最大值和最小值Java 从文件中读取成绩,java,arrays,Java,Arrays,我很难弄清楚我的编码有什么问题。它需要从文件中读取文本并打印平均值、最大值和最小值 import java.util.*; import java.io.*; public class LoopAndHalf{ public static void main(String[]args)throws FileNotFoundException{ Scanner input = new Scanner(new File("midterm.txt")); int lineN
import java.util.*;
import java.io.*;
public class LoopAndHalf{
public static void main(String[]args)throws FileNotFoundException{
Scanner input = new Scanner(new File("midterm.txt"));
int lineNo=0;
int id=0;
int grade =0;
String name;
int min=1000;
int max=-1000;
int sum=0;
int count=0;
int[] scale = new int[6];
while(input.hasNextLine()){
input.nextLine();
lineNo++;
Scanner lineScan = new Scanner(line);
id = lineScan.nextInt();
name = lineScan.next();
grade = lineScan.nextInt();
count++;
if(grade>max){
max=grade;
}
if(grade<min){
min=grade;
}
if(grade>=96){
scale[5]++;
}else if(grade>=91){
scale[4]++;
}else if(grade>=86){
scale[3]++;
}else if(grade>=81){
scale[2]++;
}else if(grade>=76){
scale[1]++;
}else{
scale[0]++;
}
}//end while loop
System.out.println("Scale array: " + Arrays.toString(scale));
System.out.println("Count: " + count);
double avg= (double) sum/count;
System.out.println("Min: " + min);
System.out.println("Max: " + max);
System.out.println("Avg: " + avg);
//draw histogram
System.out.println();
for(int i=0; i<scale.length; i++){
if(i==0){
System.out.println(" - 75: ");
}else if(i==1){
System.out.println("76 - 80: ");
}else if(i==2){
System.out.println("81 - 85: ");
}else if(i==3){
System.out.println("86 - 90: ");
}else if(i==4){
System.out.println("91 - 95: ");
}else{
System.out.println("95 + : ");
}
}//end for loop
int[] counts = new int[101]; // counters of test scores 0 - 100
while (input.hasNextInt()) { // read file into counts array
int score = input.nextInt();
counts[score]++; // if score is 87, then counts[87]++
}
for (int i = 0; i < counts.length; i++) { // print star histogram
if (counts[i] > 0) {
System.out.print(i + ": ");
for (int j = 0; j < counts[i]; j++) {
System.out.print("*");
}
System.out.println();
}
}
}//end main
}//end class
错误告诉我行不能解析为变量,但这是唯一导致我出现问题的原因。
任何指点都将不胜感激。谢谢这可能是您想要实现的目标。Java有一个内置的
BufferReader.IO
BufferedReader reader = new BufferedReader(new FileReader("midterm.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
// Do what you want
}
这可能就是你想要实现的。Java有一个内置的
BufferReader.IO
BufferedReader reader = new BufferedReader(new FileReader("midterm.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
// Do what you want
}
您正在读取一行输入,但没有将其保存在变量中。改变
input.nextLine();
到
您正在读取一行输入,但没有将其保存在变量中。改变
input.nextLine();
到
错误的意思正是它所说的。您没有名为line的变量,因此无法将其作为参数传递给Scanner的构造函数。您应该使用BufferReader错误的含义与它所说的完全相同。您没有名为line的变量,因此无法将其作为参数传递给Scanner的构造函数。您应该使用bufferreader