Hello everyone,
I have just recently started learning Java (previous Python programmer) and I am making a text based calculator program.
I have had no problems with programming it so far, and I just need help with one part of perfecting it.
package calculator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
double num1, num2, answer, loop_calc=1;
String operator, rego;
System.out.println("Welcome to the Calculator.");
while (loop_calc == 1) {
System.out.println(" ");
System.out.print("Enter first number: ");
num1 = myScanner.nextDouble();
System.out.print("Enter operator: ");
operator = myScanner.next();
System.out.print("Enter second number: ");
num2 = myScanner.nextDouble();
if (operator.equals("+")) {
answer = (num1 + num2);
System.out.println(" ");
System.out.println(num1 + " " + "+" + " " + num2 + " " + "=" + " " + answer);
System.out.println(" ");
} else if (operator.equals("-")) {
answer = (num1 - num2);
System.out.println(" ");
System.out.println(num1 + " " + "-" + " " + num2 + " " + "=" + " " + answer);
System.out.println(" ");
} else if (operator.equals("/")) {
answer = (num1 / num2);
System.out.println(" ");
System.out.println(num1 + " " + "/" + " " + num2 + " " + "=" + " " + answer);
System.out.println(" ");
} else if (operator.equals("*") || (operator.equals("x"))) {
answer = (num1 * num2);
System.out.println(" ");
System.out.println(num1 + " " + "x" + " " + num2 + " " + "=" + " " + answer);
System.out.println(" ");
} else if (operator.equals("^")) {
answer = (java.lang.Math.pow(num1, num2));
System.out.println(" ");
System.out.println(num1 + " " + "^" + " " + num2 + " " + "=" + " " + answer);
System.out.println(" ");
} else {
System.out.println(" ");
System.out.println("[INVALED OPERATOR!]");
System.out.println(" ");
}
System.out.print("Another calculation? [y/n]: ");
rego = myScanner.next();
if (rego.equals("y") || rego.equals("yes")) {
loop_calc = 1;
} else if (rego.equals("n") || rego.equals("no")) {
loop_calc = 0;
}
}
}
}
I would like to make the program so that it is as "user proof" as possible.
So here is my problem, as you can see from the code if the user types anything other than a number type in 'num1' and 'num2' the program will error and end.
I solved a problem like it with the 'else' for the 'operator' variable, but need a way to solve it for the two 'num' variables.
Any ideas or advice would be much appreciated here.
Thanks for the support,
-WolfShield