• Post Reply Bookmark Topic Watch Topic
  • New Topic

Scanner Class - useDelimiter method. A very simple exercise I'm having trouble with.  RSS feed

 
Karen Haq
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't understand why the pair of numbers is not displayed, only the "1" is ...


Here's the source code:


public class DistanceTest
{

public static void main (String [] args)

{
Scanner input = new Scanner (System.in);

System.out.print("Enter one set of coordinates like this x,y: ");

input.useDelimiter (",");

System.out.println(input.nextInt());
System.out.println(input.nextInt());

input.close();

}


}

Here's the output:

Enter one set of coordinates like this x,y: 1,2
1


 
Nick Puketza
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Karen,

I don't have the complete answer ... but I think I found a clue.
When I run your program with the following input:

1,2,

... then both numbers do appear in the output.

- Nick
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The API documentation of the Scanner class defines a token (scanned for by the nextInt() method) as follows:

A complete token is preceded and followed by input that matches the delimiter pattern.

Another thing to be aware of is that the String passed to the useDlimiter() method is actually used as a regular expression.
So, if the delimiter expression "," is used and the user inputs 1,1, what's missing that the Scanner needs to succesfully match the last token "1"?
Yep, the trailing delimiter pattern "," - try entering the following input "1,1," and you'll get the output you expected.
You'll not want the user to have to enter that trailing "," though, so solving the problem more elegantly requires a small change to the delimiter pattern. Have a look at java.util.regex.Pattern and read up on quantifiers


 
Karen Haq
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your replies, N and J!!

I'll read over the quantifiers in the Pattern Class. I may have more questions, so I'll ask you (i.e., post a topic), or I'll just post another reply to this topic.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!