Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Scanner methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Scanner methods" Watch "Scanner methods" New topic
Author

Scanner methods

Laurie carrera
Greenhorn

Joined: Jun 07, 2006
Posts: 14
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

Joined: Oct 13, 2005
Posts: 37926
    
  22
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.
 
 
subject: Scanner methods
 
Similar Threads
Help needed with Scanner
Problem with keyboard input using a Scanner object
What is wrong with this code?
delimiters and Scanner class
Need help with structure...