Reputation: 85
I'am trying to put an exception in my code. But it doesnt work fully. Im trying for user to enter integers and then adding it to a list.
how come it only works for the first input? say if the first I enter 1.0 then it will raise the error. but if I put say 10, 1.0
it doesnt produce an error. and when i print the list. there is only the 10
well this is actually correct. but i want to make it so that if anything is entered other than integer it raise an error, and does not terminate. instead ask the user to try again.
this is what my code looks like
package basic.functions;
import java.util.*;
import java.text.DecimalFormat;
public class Percent {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
reader.useDelimiter(System.getProperty("line.separator"));
List<Integer> list = new ArrayList<>();
System.out.println("Enter Integer: ");
do {
try {
int n = reader.nextInt();
list.add(Integer.valueOf(n));
} catch (InputMismatchException exception) {
System.out.println("Not an integer, please try again");
}
}
//When user press enter empty
while (reader.hasNextInt());
reader.close();
Upvotes: 0
Views: 4763
Reputation: 1553
What you are running is a do-while which will execute once before checking the condition.
So, your first input is tried to be parsed into an integer to which you have handled the exception, thus printing the error message.
If you give a non-integer anywhere other than first time, your code will just terminate the loop before trying to parse the input.
Something like the following will give you the error message properly as you expect.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
reader.useDelimiter(System.getProperty("line.separator"));
List<Integer> list = new ArrayList<>();
System.out.println("Enter Integer: ");
while (true) {
try {
int n = reader.nextInt();
list.add(Integer.valueOf(n));
} catch (InputMismatchException exception) {
System.out.println("Not an integer, please try again. Press enter key to exit");
if (reader.next().isEmpty()) {
break;
}
}
}
System.out.println(list);
reader.close();
}
Upvotes: 2
Reputation: 5705
Whenever you input a String
,reader.hasNextInt()
returns false
, and the loop terminates. Therefore, not printing anything.
However, since it is a do-while
loop, it must execute once, and therefore, if you input a String
first, then it prints out the error
This again, only happens if you press Enter after each input
Upvotes: 2