Hi eveybody,
It is a problem with Scanner class.
A few days ago I posted this:
============
/*
Hello everybody,
Since many of you may faced the problem with the Scanner class I will post this solution, there might be other solutions too.
*/
Scanner sc = new Scanner(System.
System.out.println(
int custNum = sc.nextInt()
sc.nextLine(
System.out.println(
String type = sc.next();
/*
*
You could try using sc.next(); instead of sc.nextLine(
The
problem lies in the newline character at the end of the line (when you
hit the return key) and how the Scanner class does not handle it
consistently (is it another token or not?) when reading text input.
Sometimes you will see the problem and sometimes you will not.
When you will see the problem:
The problem occurs when reading text input after reading another primitive type like a boolean, int, or double.
How to ALWAYS solve the problem:
1. Always use nextLine() instead of next() for reading text input.
2. Anytime you read a primitive and then want to read text, add a line of code
sc.nextLine(
3.
Make certain to do step 2. even if it is in a loop where we read in a
boolean at the bottom of the loop, and if they answer true, it goes to
the top of the loop and reads the next String (a text input).
reference: http://www.robocomm
*/
============
One of my colleagues replied:
************
I do not agree! Your problems with the Scanner is solved if you ALWAYS use next() and NEVER nextLine()
Instead you shall always specify the delimeter for the Scanner:
sc.useDelimiter(
So, to summarize:
Create the Scanner:
Scanner sc = new Scanner(System.
sc.useDelimiter(
and then use it..
String s = sc.next();
...to read a String, and you will not encounter any problems!
************
I have tested this for a while:
The following code that I have tested does NOT run properly:
int myInt = 0;
String myString = "";
Scanner in = new Scanner(System.
in.useDelimiter(
while(true){
if (in.hasNextInt(
myInt = in.nextInt()
System.out.println(
switch (myInt){
case 1:
System.out.println(
break;
case 2:
System.out.println(
break;
}
} else if (in.hasNext(
System.out.println(
}
Is it my problem that I cannot use Delimiters?
Thanks in advance.
[Non-text portions of this message have been removed]
Java Official Group is created for the following topics: Java 2 Enterprise Edition - J2EE, Java 2 Standard Edition - J2SE, Java 2 Micro Edition - J2ME, XML, XSL, XSD, XPATH, Web Services, Jini, JXTA for all type of Java Geeks.
Whoever posts spam / ads / job related message will be BANNED IMMEDIATELY
No comments:
Post a Comment