导入 java.util.Scanner;
公共类 MathFun { public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x = 1;
System.out.println(" Enter a math operation: ");
String expr = input.next();
int pos = expr.indexOf("-");
if ( pos > 0) {
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
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 ");
}
}
}
这可以编译,但我很难初始化 pos = expr.inexOf();。我将如何解决这个问题,以便我的 if 语句开始工作并能够使用字符串?非常感谢你的帮助!