Scanner works in JCreator but doesn't when run from Command Prompt?
Nov 4, 2009 12:48 AM
Can someone tell me why I can run this program in JCreator with no problems, but when I run it with the Command prompt it throws a java.util.InputMismatchException if I input anything?
import java.util.Scanner;
publicclass tester {
publicstaticvoid main(String[] args) {
Scanner in = new Scanner(System.in).useDelimiter("\n");
System.out.println("Type either 1 or 2");
int temp = in.nextInt();
System.out.println("");
if (temp == 1)
System.out.println("you typed 1");
if (temp == 2)
System.out.println("you typed 2");
else
System.out.println("you typed something else!");
}
}
SamColt wrote:
Can someone tell me why I can run this program in JCreator with no problems, but when I run it with the Command prompt it throws a java.util.InputMismatchException if I input anything?
Scanner in = new Scanner(System.in).useDelimiter("\n");
Why are you explicitly specifying the new line character as the delimiter? Try running it without that...
Re: Scanner works in JCreator but doesn't when run from Command Prompt?
Nov 4, 2009 11:43 AM
(reply 3
of 6) (In reply to
#1 )
I need the delimiter because it is an essential part to the actual program. Mostly I'm just wondering why it runs with JCreator but throws an error in the command prompt.
Re: Scanner works in JCreator but doesn't when run from Command Prompt?
Nov 4, 2009 11:50 AM
(reply 4
of 6) (In reply to
#3 )
Correct
SamColt wrote:
I need the delimiter because it is an essential part to the actual program. Mostly I'm just wondering why it runs with JCreator but throws an error in the command prompt.
It's giving you that exception because from a Windows console, a newline is "\r\n". Because the scanner encounters the "\n", and you've explicitly set that as the delimiter, it thinks that "\r" must be part of the first token, and so it tries to parse it as part of an integer when clearly it's not. JCreator must send just "\n" to stdin when you press Enter.
If you just leave the Scanner at the default delimiter, it will correctly handle both "\n" and "\r\n" as newlines.
Re: Scanner works in JCreator but doesn't when run from Command Prompt?
Nov 4, 2009 12:05 PM
(reply 5
of 6) (In reply to
#4 )
endasil wrote:
It's giving you that exception because from a Windows console, a newline is "\r\n". Because the scanner encounters the "\n", and you've explicitly set that as the delimiter, it thinks that "\r" must be part of the first token, and so it tries to parse it as part of an integer when clearly it's not. JCreator must send just "\n" to stdin when you press Enter.