2

This is the data in myFile.txt, the first line has 4 tokens, the second has 3, and the last has 4 tokens. The last token, an int, indicates the persons salary. If no salary, the no integer, and thus one less token.

Peter, 22, m, 1200
Nina, 24, f
Oscar, 40,m, 40000

Obviously the while loop further down, would give me an inputMisMatchException, so is there a good way for reading textfiles where each line my have one extra/less token?

while(input.hasNextLine()) {
     String name = input.next();
     int age = input.nextInt();
     String gender = input.next();
     int salary = input.nextInt();
}
0

2 Answers 2

3

In this case, you can add hasNextInt to check if the next token is integer or not:

while(input.hasNextLine()) {
     String name = input.next();
     int age = input.nextInt();
     String gender = input.next();
     if (input.hasNextInt()) {
         int salary = input.nextInt();
         ...
     }
}

However, this is not universal: what if the first column of the file is also an int?

A better approach would be to read your input line-by-line, split on commas and spaces, and then parse the data based on the number of available tokens:

while(input.hasNextLine()) {
     String line = input.nextLine();
     String[] tokens = input.split(" ,");
     String name = tokens[0];
     int age = Integer.valueOf(tokens[1]);
     String gender = tokens[2];
     if (tokens.length > 3) {
         int salary = Integer.valueOf(tokens[3]);
         ...
     }
}
Sign up to request clarification or add additional context in comments.

Comments

1
  • You could read the entire line using String line = input.nextLine(); and then use line.split(", "); to split the tokens and store them in an array.

  • Then you can iterate through the array and get the values as array[0] is name and array[1] is age and so on...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.