Please held. What is wrong with my code? I am a beginner ;)
In this program the user is buying some online stuff. A menu is displayed with the available stuff. The user is asked to enter the code of the object he needs. Until the user enter "XX" the program keeps looping.
Code java:
System.out.print("ENTER CODE (XX to Stop): ");
System.out.println();
System.out.print("CODE: ");
String code = in.nextLine();
System.out.print("QUANTITY: ");
int quantity = in.nextInt();
while (code.compareTo("XX")!=0 )
{
System.out.print("CODE: ");
code = in.nextLine();
System.out.print("QUANTITY: ");
quantity = in.nextInt();
}
Can someone please compile the program and tell me what is wrong with my program? When the user enter the second object the following error is coming up, If the user enters "XX" the program compiles correctly:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at ass2012.Ass2012.main(Ass2012.java:51)
Java Result: 1
Looking forward to hear from you! THANKS
Re: Please held. What is wrong with my code? I am a beginner ;)
The issue is that nextInt() doesn't consume the end of line characters after you enter in a number and press enter. The solution is to add in a dummy nextLine() call that will consume this character.
Re: Please held. What is wrong with my code? I am a beginner ;)
oucch that's a tricky one! thanks for your feedback!