+ 1
Why my java resume its getting exception error?
when I use the set method after that the get method it doesn't work. I think it's a error on scanner https://code.sololearn.com/cdNx5La02lor/?ref=app https://code.sololearn.com/cdNx5La02lor/?ref=app
1 Antwort
+ 4
The issue that you're having is with your use of the Scanner. When you use .nextInt() or .nextDouble() the method does not consume the return or '\n' character from the end of the line, leaving it in the stream for next call that will consume it such as .next() or .nextLine().
There are a couple of ways you can fix this issue.
First you could make a call to .next() or .nextLine() directly after a call to .nextInt() or .nextDouble() that isn't being set to any variable prior to the next call to .next() or .nextLine() so that the '\n' character is consumed and doesn't cause that .next()/.nextLine() call that you wish to capture input with to only catch that '\n' character.
...
nombre = mem.nextLine();
...
prieco = mem.nextDouble();
...
x = mem.nextInt();
mem.next(); // catch the '\n' remaining from the previous line
...
nombre = mem.nextLine();
A second option would be to only use .nextLine() and/or .next() with the Scanner and convert each input to the desired type.
for an int you would surround it with Integer.parseInt() and for a double Double.parseDouble()
...
nombre = mem.nextLine();
...
prieco = Double.parseDouble(mem.nextLine());
...
x = Integer.parseInt(mem.nextLine());
...
nombre = mem.nextLine();
A third less popular option would be to use one Scanner for Strings .nextLine() and another for numerical types (Int, Double, etc) .nextInt(), .nextDouble().