Scanner.useDelimiter("\n") Problem
Hey guys I am having some trouble when I use Scanner.UseDelimeter("\n") basically I have:
Code :
Scanner s = new Scanner(System.in);
s.useDelimiter("\n");
int amount;
System.out.println("Enter the amount needed: ")
amount = s.nextInt();
After I enter the integer for the amount, the program crashes. I use the delimiter for the scanner as I am using scanner.NextLine() later in the program.
Thanks
Re: Scanner.useDelimiter("\n") Problem
Quote:
the program crashes.
Please copy and paste the full text of the error message here.
Re: Scanner.useDelimiter("\n") Problem
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at DessertManager.main(DessertManager.java:39)
Line 39 is amount = s.nextInt();
Re: Scanner.useDelimiter("\n") Problem
Quote:
java.util.InputMismatchException
This says that the input being read was not an integer.
What did you type into the console that caused this?
Re: Scanner.useDelimiter("\n") Problem
Just the number 1.
If I remove the s.useDelimiter("\n");
There is no problems, but I was told to use this to solve another problem, which is using nextLine() before a nextInt().
Re: Scanner.useDelimiter("\n") Problem
I guess using the \n changes the way Scanner works.
Here is what I tried and what I got:
Code :
Scanner s = new Scanner(System.in);
s.useDelimiter("\n"); //<<<<<<<<<<
System.out.println("Enter the amount needed: ");
System.out.println("hasNextInt=" + s.hasNextInt() + ", hasNext=" + s.hasNext());
String line = s.nextLine();
System.out.println("line=" + line + "<");
/*
D:\JavaDevelopment\Testing\ForumQuestions6>java TestCode5
Enter the amount needed:
1 2 the end
hasNextInt=false, hasNext=true
line=1 2 the end<
*/
Re: Scanner.useDelimiter("\n") Problem
Yeah the \n changes it. I might just not use it, and use my other solution to the problem I was having. Appreciate your help anyway!