I am writing a program that reads from a file titled “grades.txt” and displays the student’s name, three grades, and the average of those three grades.
The text file looks like this:
Bobby Doe 65 65 65 Billy Doe 100 100 95 James Doe 85 80 90
Here is the code. I am able to read from the file and output everything correctly.
import java.util.Scanner; // Needed for Scanner class.
import java.io.*; // Needed for I/O class.
public class TestScoresRead
{
public static void main(String[] args) throws IOException
{
// Open the file
File file = new File("Grades.txt");
Scanner inputFile = new Scanner(file);
// Read lines from the file
while (inputFile.hasNext())
{
String firstName = inputFile.next();
String lastName = inputFile.next();
double grade1 = inputFile.nextDouble();
double grade2 = inputFile.nextDouble();
double grade3 = inputFile.nextDouble();
String nextLine = inputFile.nextLine();
int total = (int)grade1 + (int)grade2 + (int)grade3;
int average = total / 3;
System.out.println("Name: t" + firstName + " " + lastName);
System.out.println("Test 1:t" + grade1);
System.out.println("Test 2: t" + grade2);
System.out.println("Test 3: t" + grade3);
System.out.println("");
System.out.println("Average: " + average);
if (average < 60)
System.out.println("Grade : t F");
else if (average < 70)
System.out.println("Grade : t D");
else if (average < 80)
System.out.println("Grade: t C");
else if (average <90)
System.out.println("Grade: t B");
else
System.out.println("Grade: t A");
System.out.println("");
}
inputFile.close();
}
}
However, I keep getting this error and I am not sure why:
Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1540) at TestScoresRead.main(TestScoresRead.java:21)
From the research I’ve done, I believe it has something to do with going from nextLine to nextDouble, and the n being stuck in the keyboard buffer.
Or maybe I’m not using hasNext right?
How can I fix the error?
Advertisement
Answer
remove this line
String nextLine = inputFile.nextLine();