I'm new to Java and I'm trying to use a scanner to read in some data from a text file. The scanner reads in the string and integer data members fine, but when it reaches a double it throws an InputMismatchException.
The format of the text file looks like this...
Lastname,Firstname,0,0.0
Smith,John,10,2.456
Jones,William,15,3.568
Here is my code...
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
public class Student {
int age;
double gpa;
String firstName;
String lastName;
public static void main (String[] args) {
int iNum = 0;
double dNum = 0.0;
String str1 = "";
String str2 = "";
List<Student> listOfObjects = new ArrayList<>();
try {
Scanner src = new Scanner(new
File("data.txt")).useDelimiter(",|\r\n|\n");
while (src.hasNext()) {
str1 = src.next(); //last name
str2 = src.next(); //first name
iNum = src.nextInt(); //age
dNum = src.nextDouble(); /* gpa - having trouble reading these doubles with Scanner */
Student object = new Student(str1, str2, iNum, dNum);
listOfObjects.add(object); //add new object to list
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
for (Student a: listOfObjects) // printing the sorted list
System.out.print(a.getStudentLastName() + ", " +
a.getStudentFirstName() +
", " + a.getStudentAge() + ", " + a.getStudentGpa() + "\n");
}
public Student(String str1, String str2, int iNum, double dNum){
this.lastName = str1;
this.firstName = str2;
this.age = iNum;
this.gpa = dNum;
}
public String getStudentFirstName() {
return firstName;
}
public String getStudentLastName() {
return lastName;
}
public int getStudentAge() {
return age;
}
public double getStudentGpa() {
return gpa;
}
I tried setting the locale to US and tried messing with the delimiters, but nothing seems to be working.