Sunday, September 30, 2018

java - Reading textfile with Scanner results in 'InputMismatchException'

Using parseInt() and parseDouble() methods in combination with nextLine() method will solve your problem. I have written some code:


public class Person{
private String name;
private String gender;
private int age;
private double weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
}

and


import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class PersonTest {
public static void main(String[] args) throws FileNotFoundException {
File inputFile = new File("data.txt");
Scanner sc = new Scanner(inputFile);
ArrayList peopleList = new ArrayList();
Person p;
while (sc.hasNext()){
p = new Person();
p.setName(sc.nextLine());
System.out.println(p.getName());
p.setGender(sc.nextLine());
System.out.println(p.getGender());
p.setAge(Integer.parseInt(sc.nextLine()));
System.out.println(p.getAge());
p.setWeight(Double.parseDouble(sc.nextLine()));
System.out.println(p.getWeight());
peopleList.add(p);
}
sc.close();
}
}

I think the problem why your code didn't work is that after nextDouble() found 85.83, the scanner skipped that number and was still at 4th line. When you called nextLine() in the second loop, it returned the rest of 4th line, which was blank.
Using my solution, you can take a full line and then easily convert it to integer number or double number.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...