I refreshing my Java skills, say we've got this code
public class HelloWorld extends Exception {
public static int tenMultiplication(int x) {
for (int i = 2; i < 11; i++) {
System.out.println(x * i);
}
return x;
}
public static String scanExpression() {
Scanner scan = new Scanner(System.in);
String exp = "";
do {
System.out.println("Please enter a number:");
try {
exp = scan.nextLine();
int result = Integer.parseInt(exp);
tenMultiplication(result);
} catch (NumberFormatException e) {
System.out.println("Please enter a number: ");
}
} while (exp.matches("-?\\d+") || exp == "exit");
return exp;
}
public static void main(String args[]) throws Exception {
scanExpression();
}
}
Program logic: Program asks for an input, and draws a row of multiplication table till 10; any time you can exit by typing "exit", everything else is an error.
Every time I write an incorrect number, it will simply catch an error and exit the program. What is the best way with going about iteratively catching errors if you consecutively type non-Ints and not "exit" to exit the program? I tried putting
exp = scan.nextLine();
int result = Integer.parseInt(exp);
tenMultiplication(result);
But when trying to write an error here, it throws the error again, which defeats the point of my try { } catch blocks.