Morgan Henry
Morgan Henry

Reputation: 5

Using Scanner hasNext() and hasNextLine() to retrieve 2 elements per line

In Java, if you were given a text file with two elements per line, how can we grab those elements separately?

For example say we have a 5 line text file with the following:

a morgan
b stewart
c david 
d alfonso
e brittany

and let's say we want to store the single char in a variable and the name in another variable. How do we do this is java?

I have implemented some code somewhat like this:

while(scanner.hasNextLine()){
  for(int i = 0; i < 2; i++){
  char character = scanner.hasNextChar(); // doesn't exist but idk how 
  String name = scanner.hasNext(); 
}
}

Basically I have a while loop reading each 2 elements line by line and in each line there is a for loop to store each element in a variable. I am just confused on how to extract each separate element in java.

Upvotes: 0

Views: 2355

Answers (2)

davidxxx
davidxxx

Reputation: 131436

You can split the line with the whitespace character by using the String.split(String regex) method.
It will produce an array of two String.

If you invoke while(scanner.hasNextLine()){ to get an input, you should invoke String name = scanner.nextLine(); to retrieve the input.

The hasNext() method returns a boolean to indicate if this scanner has another token in its input.
Doing while(scanner.hasNextLine()){ and scanner.hasNext() is redundant.

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56453

Considering that you're using scanner.hasNextLine() as your loop condition. You can split the String then collect the result as needed.

while (scanner.hasNextLine()){
     String[] result = scanner.nextLine().split(" "); 
     char character = result[0].charAt(0);
     String name = result[1];
}

Upvotes: 1

Related Questions