My assignment says to throw a try and catch for this:
- If the user does not enter at least 3 tokens
- If the user does not enter valid numbers for tokens one and three.
I tried researching it and I can't seem to find the exception that would go by this. Now my exception seems to work for the two conditionals above, but my instructor wishes for me to have two catches, not one.
I want to be able to crash this program so I can finally get another throw and catch or modify this program so that the exception would catch one thing specifically (like only if the user does not enter at least 3 tokens).
If I try do either of the things above to crash this program, by the way, it will always give me my error message so it clearly seems to cover the two things I have above.
My exception covers the two things I need to catch, but I need two catches, not one.
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Driver {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
StringTokenizer st;
String input, tok1, tok2, tok3;
double dtok1, dtok3;
boolean loop = true;
//input
System.out.println("Simple calculator program");
System.out.println("This program will only except a math expression with");
System.out.println("2 operands and 1 operator. Exceptable operators");
System.out.println("are +, -, *, /, and %. For example, 2*3 or 6%4.");
while (loop) {
System.out.print("\nplease enter an expression or q to quit: ");
try {
input = sc.next();
if (input.equalsIgnoreCase("q")) {
loop = false;
} else {
//calculations
st = new StringTokenizer(input,"+-*/%",true);
tok1 = st.nextToken();
tok2 = st.nextToken();
tok3 = st.nextToken();
dtok1 = Double.parseDouble(tok1);
dtok3 = Double.parseDouble(tok3);
System.out.println(input + "=" +
singleExpression(dtok1,dtok3,tok2));
}
} catch (Exception NoSuchElementException) {
System.out.println ("Error! Please enter 2 operands and 1 operator!");
}
}
}
static double singleExpression (double num1, double num2, String operator) {
double output = 0.0;
if (operator.equals("+")) {
output = num1 + num2;
} else if (operator.equals("-")) {
output = num1 - num2;
} else if (operator.equals("*")) {
output = num1 * num2;
} else if (operator.equals("/")) {
output = num1 / num2;
} else if (operator.equals("%")) {
output = num1 % num2;
} else {
output = 0;
}
return output;
}
}