Scanner input = new Scanner(System.in);
int x = 0;
System.out.println(" Enter a math operation: ");
String expr = input.next();
int pos = expr.indexOf("+");
if ( pos >= 0) {
int op1 = Integer.parseInt(expr.substring(0, pos));
int op2 = Integer.parseInt(expr.substring( pos - x , expr.length()));
System.out.println( op1 + op2);
} else
if (pos == expr.indexOf("-")) {
int op1 = Integer.parseInt(expr.substring(0, pos));
int op2 = Integer.parseInt(expr.substring( pos - x , expr.length()));
System.out.println( op1 - op2);
} else
if (pos == expr.indexOf("/")) {
int op1 = Integer.parseInt(expr.substring(0, pos));
int op2 = Integer.parseInt(expr.substring( pos - x , expr.length()));
System.out.println( op1 / op2);
} else
if (pos == expr.indexOf("%")) {
int op1 = Integer.parseInt(expr.substring(0, pos));
int op2 = Integer.parseInt(expr.substring( pos - x , expr.length()));
System.out.println( op1 % op2);
}
else {
System.out.println(" Invalid operation ");
}
}
}
ALthough this gets compiled, the program automatically says
an ex out of range: -1
at java.lang.String.substring(String.java:1937)
at MathFun.main(MathFun.java:21)
Is there something wrong with the loop? I just want to make a simple loop that lets the user enter a string 2+2 and let the loop read that out as a string and print the result. Thank You!