从文件中读取成绩

时间:2014-10-28 20:28:22

标签: java arrays

我无法弄清楚编码问题是什么。它需要从文件中读取文本并打印avg,max和min。

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

不断给我带来麻烦的是

Scanner lineScan = new Scanner(line);

错误告诉我该行无法解析为变量,但这是导致我出现问题的唯一因素。 任何指针将不胜感激。感谢

2 个答案:

答案 0 :(得分:3)

您正在阅读一行输入,但您没有将其保存在变量中。变化

input.nextLine();

String line = input.nextLine();

答案 1 :(得分:2)

这可能是您想要实现的目标。 Java有内置BufferReader.IO

BufferedReader reader = new BufferedReader(new FileReader("midterm.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
   // Do what you want
}