I have an assignment for school that is going to be tested using a premade textfile that feeds data into the program. My problem is that this premade text file crashes the program, even though it works without a problem when you type the data in manually. I've managed to recreate the problem in a much smaller program:
import java.util.Scanner;
import java.util.ArrayList;
public class DoubleTest {
public static void main(String[] args){
ArrayList<String> fNames = new ArrayList<>();
ArrayList<String> sNames = new ArrayList<>();
ArrayList<Double> scores = new ArrayList<>();
Scanner keyboard = new Scanner(System.in);
int i = 1;
while(i != 0){
System.out.println("First name (quit by typing 0): ");
String fName = keyboard.nextLine();
if(fName.equals("0")){
i = 0;
}else{
System.out.println("Result: ");
double score = keyboard.nextDouble();
keyboard.nextLine();
System.out.println("Last name: ");
String sName = keyboard.nextLine();
fNames.add(fName);
sNames.add(sName);
scores.add(score);
}
}
for(String s : fNames){
System.out.println(s);
}
for(String s : sNames){
System.out.println(s);
}
for(Double d : scores){
System.out.println(d);
}
}
}
Now if I simply write the input as it goes along, everything works fine. But if I use a premade text file that I just copy paste it throws an exception. The program asks for a firstname, then a result (double) and then the last name. Then you can either enter in a new first name or quit by typing 0. This is the textfile
name1
20
name1
30
name2
40
name2
name3
50
name3
name4
60
name4
And this is the exception:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at DoubleTest.main(DoubleTest.java:21)
Any ideas on how to fix this? And again, it doesn't throw an exception when I type it in manually!