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.
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.
Since you know the first int in each line ISNT a grade, you can save each line using
someString = in.nextLine()
whilein.hasNextLine()
and then iterate over each saved string skipping the first integer using a newScanner
instance for each line.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:
Then you can use a
for
loop as such...And contain this entire process in a
while
loop to iterate over every line.