I am finally (almost) done with a little calculator project that I have been working on. Currently, it works with addition, subtraction, multiplication, division, mod, squaring, and negation of doubles and responds to some strings such as "exit", "clear", and "help".
I just need help implementing a try and catch block to return a message in the console such as "Invalid Input" whenever the user enters anything that is not a number after the console says "Enter first number" or "Enter second number".
I have messed around with a few different methods but nothing seems to be working. Advice would be greatly appreciated. Code:
import java.util.Scanner;
public class exit {
static double num1;
static double num2;
static String operation;
public static void main(String[] args) {
boolean run = true;
while (run) {
System.out.println(" Enter: \n \b help for all usable operations \n continue to use the calculator");
Scanner input = new Scanner(System.in);
String str1 = input.next();
if (str1.equals("exit")) {
System.exit(0);
} else if (str1.equals("clear")) {
System.out.println("0.0");
} else if (str1.equals("help")) {
System.out.println("please enter:\n + for addition \n - for subtraction \n * for multiplication \n / for division \n -x for negation \n x^2 for squaring\n % for mod \n remember to only input integer or double values\n");
} else if (str1.equals("continue")) {
System.out.println("\nEnter the first number:");
num1 = input.nextInt();
System.out.println
("Display:" + num1);
System.out.println("Please enter operation:");
operation = input.next();
System.out.println("Enter the second number:");
num2 = input.nextInt();
System.out.println("Display:" + num2);
if ("+".equals(operation)) {
System.out.println((num1 + num2));
} else if ("-".equals(operation)) {
System.out.println((num1 - num2));
} else if ("/".equals(operation)) {
System.out.println((num1 / num2));
} else if ("*".equals(operation)) {
System.out.println((num1 * num2));
} else if ("-x".equals(operation)) {
System.out.println(-num1);
} else if ("x^2".equals(operation)) {
System.out.println(num1 * num1);
} else if ("sqrt".equals(operation)) {
System.out.println(Math.sqrt(num1));
}
}
}
}
}