Reading the next line in a text file

2019-09-16 03:49发布

问题:

I'm trying to read input from a text file that will be formatted like this:

2 80 97 
5 69 79 89 99 58 
7 60 70 80 90 100 0 59

The first number of each line is the number of "grades" per "section."

I got my program to read one section, but I can't figure out how to make it read how many sections there will be, and then read the next line(s).

I think I can put my current code in a count controlled loop that will first read how many sections there are, and run the loop that many times. I just don't know how to convert that idea to code.

Here is the revevant code section:

public static void main(String args[]) throws Exception 
{
  Scanner in = new Scanner(new File("prog2test.txt")); 

  //int sections = (in.nextInt());
  int scores = (in.nextInt());
  int scoresForAverage = scores;
  int scoreTotals = 0;
  double average = 0;
  int A = 0;
  int B = 0;
  int C = 0;
  int D = 0;
  int F = 0;

  int highest = 0;
  int lowest = 100;
  while (scores > 0 && in.hasNextInt())
  {
     int grade = in.nextInt();
     if (grade >= 90)
        A++;
     else if (grade >= 80)
        B++;
     else if (grade >= 70)
        C++;
     else if (grade >= 60)
        D++;
     else
        F++;

     if (grade > highest) 
        highest = grade;
     if (grade < lowest)
        lowest = grade;

     scores--;
     scoreTotals = (scoreTotals + grade);
   }  

  average = scoreTotals/scoresForAverage;

  System.out.println("Scores for section 1");
  System.out.println("A's: " + A);
  System.out.println("B's: " + B);
  System.out.println("C's: " + C);
  System.out.println("D's: " + D);
  System.out.println("F's: " + F);
  System.out.println("Lowest score: " + lowest);
  System.out.println("Highest score: " + highest);
  System.out.println("Average: " + average);

EDIT: Updated with complete method.

回答1:

Since you know the first int in each line ISNT a grade, you can save each line using someString = in.nextLine() while in.hasNextLine() and then iterate over each saved string skipping the first integer using a new Scanner instance for each line.



回答2:

If you are using Scanner, you can use the method hasNext();

This will be true as long as there are any strings in the text separated by a whitespace.



回答3:

You can read the entire line, then use the String.split method to split this into an array using a space delimiter.

After you read the line:

String grades[] = line.split(" ");

Then you can use a for loop as such...

for(int i=1; i<grades.length; ++i) { 
//start an index 1 to skip the non-grade first number on line
    int grade = parseInt(grades[i]);
    if (grade >= 90)
        A++;
    //etc on down the line
}

And contain this entire process in a while loop to iterate over every line.