First of all, it is difficult to know what you are trying to do. The variables
credit,
noOfItems and
prices are never defined. But as
Scanner#nextInt() will always give us an integer and
Scanner#nextLine() will return a String (both according to the
Java API docs) I'm guessing you have a definition similar to this one:
- int credit, noOfItems;
-
String prices;
OK, next step. When I add these and run the program, it throws an
InputMismatchException when I would expect to input the prices and enter anything but an integer. But wait, it already output the line
Why so? Well,
nextLine() will scan for the rest of the line, remove any line separator and return the result. This means, that it won't wait for you to input something but will rather just return an empty String. Change the last printout to
- System.out.println("no of pr is : '" + prices + "'");
and you'll see an empty result. It will then continue with the second reading of the
credit
So, what's the solution? Well, depending on what exactly you're expecting for the
prices variable, use a different method from the
Scanner class.
PS.: You don't need two Scanners. Just use
input rather than
in inside the loop.