I am trying to make a simple calculator program. However, I am also trying to make it so that if the user enters in something that is not a double, it will ask again for a double. However, when I try to enter in something like "e" for a double, it gave me an input.mismatch.exception. I put in a try catch block, and all that does is infinitely asks for input without giving a chance to put input, then errors out because it overloads the RAM giving me a stackoverflow (nice) error. code:
/**
* @author camper
* Jul 1, 2019
* 3:28:04 PM
*/
import java.util.Scanner;
public class io2 {
static double num1;
static String op;
static double num2;
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
doStuff();
}
public static void doStuff() {
getNum1();
getOp();
getNum2();
calc(num1, op, num2);
}
public static void calc(double a, String c, double b) {
if (c.equals("+")) {
System.out.println(a + b);
} else if (c.equals("-")) {
System.out.println(a - b);
} else if (c.equals("*")) {
System.out.println(a * b);
} else if (c.equals("/")) {
System.out.println(a / b);
} else {
System.out.println("That ain't no operator");
doStuff();
}
}
public static void getNum1() {
try {
System.out.println("Enter your first number:");
num1 = input.nextDouble();
}catch (Exception e) {
getNum1();
}
}
public static void getOp() {
System.out.println("Enter what operator you want (+,-,*,/):");
op = input.nextLine();
}
public static void getNum2() {
System.out.println("Enter your second number:");
num2 = input.nextDouble();
}
}