Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Scanner methods

 
Laurie carrera
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I put together code to read a line of user input which should be in the form of a sentence. Then split it into its constituent words, ignoring punctuations and spaces,these words are then stored in an array, and the array is printed out.
I used the scanner class to read user input.
I used two methods from the scanner class:next() and nextLine() and got different results which I am having a tough time understanding.
Both methods seem to read the user input, but when using the next() method, my code reads only the first word in the sentence and ignores the rest. While the nextLine() method processed the code perfectly and split all the whole sentence.

I used the regex \W to split the line.

The 1.5 API defines the methods as such:
next()-Finds and returns the next complete token("what exactly is a token?") from this scanner.
nextLine()-Advances this scanner past the current line and returns the input that was skipped.

The first one returns the next token, the second one returns a previous line of input. Please explain.

My code with nextLine()(works as per requirements):

public void Splitstrg()
{
String br[]= new String[50];
int i;
String empt = "",line;
System.out.print("Please enter a sentence\n");
Scanner input = new Scanner(System.in);
line = input.nextLine();
br = line.split("[\\W]");
//System.out.println(br[0]+br.length);
for(i=0;i<br.length;i++)
{
if (br.compareTo(empt)==0)
continue;
System.out.println(br);
}
}

My code with next()(Ignores all except first word):
public void Splitstrg()
{
String br[]= new String[50];
int i;
String empt = "",line;
System.out.print("Please enter a sentence\n");
Scanner input = new Scanner(System.in);
line = input.next();
br = line.split("[\\W]");
//System.out.println(br[0]+br.length);
for(i=0;i<br.length;i++)
{
if (br.compareTo(empt)==0)
continue;
System.out.println(br);
}
}

Any help is appreciated.>
 
Campbell Ritchie
Sheriff
Posts: 48921
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The next() method. . . reads only the first word in the sentence and ignores the rest.
Have you looked in the API about Scanner? That is what it is supposed to do.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic