Scanning a String with a comma
I have created a Scanner
with system.in
.
How do I allow an input to be able to have commas in it without going to the next input?
For example:
System.out.print("Enter City, State.");
String location = scan.nextLine();
I cannot enter city,state
because the la开发者_如何学运维nguage thinks I want to proceed to the next scanning input question. How do I allow commas in a scanning string?
*Whole Code
Scanner scan1 = new Scanner (System.in);
System.out.print ("City, State: ");
String location1 = scan.nextLine();
System.out.print ("Enter number: ");
number1 = scan.nextDouble();
System.out.print ("Enter number: ");
number2 = scan.nextDouble();
System.out.print ("City, State: ");
String name2 = scan1.nextLine();
System.out.print ("Enter #: ");
number3 = scan.nextDouble();
System.out.print ("Enter #: ");
number4 = scan.nextDouble();
scan.nextLine();
will return the entire line, commas or not.
If that isn't what's happening, then the problem must be elsewhere and you should provide more code.
Re: full code: That still works. What is the error you're getting / unwanted behavior?
What I think is happening is that the nextLine()
is catching the end-of-line character from your previous input.
What happens:
- Suppose you enter a number like
12.5
and pressenter
. - The buffer that
Scanner
reads from now contains12.5\n
where\n
is the newline character. Scanner.nextDouble
only reads in12.5
and\n
is left in the buffer.Scanner.nextLine
reads the rest of the line, which is just\n
and returns an empty string. That's why it skips to the next input: it already read "a line".
What I'd do to fix it:
System.out.print ("City, State: ");
String name2;
do{
name2 = scan1.nextLine();
}while( name2.trim().isEmpty() );
What this loop does is it keeps reading the next line until there is a line with something other than whitespace in it.
One possible solution: get the next line as you're doing and then use String#split on it to split on the comma (either that or use a second Scanner object that takes that String as input). If there is only one comma, then splitting on "," will give you an array that holds two Strings. You'll need to trim the second String to get rid of whitespace, either that or split on a more fancy regular expression.
You can either use split as mentioned above, or you could create another scanner on the next line, this would especially be useful if you have more than one fields separated by a ",".
System.out.print ("City, State: ");
Scanner temp = new Scanner(scan.nextLine());
temp.useDelimiter(",");
while(temp.hasNext()){
//use temp.next();
//Do whatever you want with the comma separated values here
}
But I still suggest that if you are just looking at something as simple as "City,State" , go for split.
精彩评论