0

I'm fairly new to java and I'm a little stuck with how I can extract each string in a line from a file and then setting those in values in 6 different variables using Scanner. This is what I have so far:

File fileName = new File("studentInfo.txt");
Scanner file = new Scanner(fileName);
while(file.hasNext()){
    String s = file.next();
    System.out.println(s);
}
file.close();

studentInfo.txt

John Smith 1990 12 25 Junior
Jesse Jane 1993 10 22 Freshman
Jack Ripper 1989 01 14 Senior

My output, prints:

John
Smith
1990
12
25
Junior

So basically I need to set John to firstName, Smith to lastName, 1990 to year, 12 to month, 25 to day, and Junior to classYear, and then loop through the next line and so on. Can someone help? Thanks in advance.

1
  • 5
    Why not consider creating a Person object with all these 6 properties and then setting those properties in your loop? I'm assuming somewhere further down the line you would need access to these values again. It'd be difficult to just assume n number of strings if you don't know how many lines you will have. Commented Oct 15, 2015 at 23:51

1 Answer 1

2

Use one scanner for the lines and one for reading each line:

Scanner lineScanner = new Scanner(fileName);
while(file.hasNextLine()){
    String line = lineScanner.nextLine();
    // parse the line
    Scanner sc = new Scanner(line);
    String firstName = sc.next();
    String lastName = sc.next();
    int year = sc.nextInt();
    int month = sc.nextInt();
    int day = sc.nextInt();
    String classYear = sc.next();
    sc.close();
    // use the variables
    // ...
}
file.close();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.