Reputation: 101
I have a txt file with name and last name/s and I need to create users from it. For example, I have in the txt values like this:
Beckham, David
Lopez Vega, Maria
Graham Daniels, Luke
The problem is that users are created just with the first last name and the name (ignoring second last name in case it have it). I don't know how to take that information and create an object with it. The object class is simple:
public class Student {
private String name;
private String lastName;
public Student(String name, String lastName) {
this.name= name;
this.lastName= lastName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getlastName() {
return lastName;
}
public void setlastName(String lastName) {
this.lastName = lastName;
}
I've tried this:
Scanner input = new Scanner(new File("Students.txt"));
List<Student> students= new ArrayList<Student>();
while(input.hasNext()) {
String name= input.next();
String lastName = input.next();
Student student= new Student(name, lastName);
students.add(student)
}
But it doesn't works. I've being trying for a while but I can't get from the file just the info I need.
Upvotes: 2
Views: 146
Reputation: 311808
I'd read an entire line and parse it by calling split
s:
Scanner input = new Scanner(new File("Students.txt"));
List<Student> students = new ArrayList<Student>();
while(input.hasNextLine()) {
String line = input.nextLine();
String[] splitLine = line.split(", ");
String name = splitLine[1];
String[] splitLastName = splitLine[0].split(" ");
String lastName = splitLastName[0];
Student student = new Student(name, lastName);
students.add(student);
}
Upvotes: 3