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();
System.out.println("got: " + list);after that close() statement ... and everything works fine. I can enter: 10 20 30 (with ENTER inbetween!) ... and 10, 20 , 30 is printed. Thus: unable to reproduce!