import java.util.Scanner;
public class MathFun {
public static void main(String[] args) {
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 ");
}
}
}
虽然这是通过javac,程序会自动说
an ex out of range: -1
at java.lang.String.substring(String.java:1937)
at MathFun.main(MathFun.java:21)
循环有问题吗? 我只想创建一个简单的循环,让用户输入一个字符串2 + 2,然后让循环读出该字符串并打印结果。谢谢!
答案 0 :(得分:1)
您的代码中存在许多问题。
string expr = in.next();
应为String expr = in.next();
pos
变量。严重的错误。int pos = expr.indexOf();
//索引input
而不是in
。 这些只是编译时错误。修复它们,然后查看程序的行为