1.在控制台输入四则运算表达式,输出计算结果。
控制台输入输出如下:
输入:1+2 输出:3
输入:2-1 输出:1
输入:1*2 输出:2
输入:2/1 输出:1
输入:2/0 输出:除数不能为0
输入:1#2 输出:输入错误
import java.util.Scanner;
public class Test01 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("请输入");
while (true) {
String s1 = s.next();
String[] s2 = s1.split("[* + -/]");
if (s2.length == 2) {
int a1 = Integer.valueOf(s2[0]);
int a2 = Integer.valueOf(s2[1]);
int result = 0;
if (s1.indexOf("+") > 0) {
result = a1 + a2;
} else if (s1.indexOf("-") > 0) {
result = a1 - a2;
} else if (s1.indexOf("*") > 0) {
result = a1 * a2;
} else if (s1.indexOf("/") > 0) {
if (a2 != 0) {
result = a1 / a2;
} else {
System.out.println("除数不能为0");
break;
}
}
System.out.println(result);
} else {
System.out.println("错误");
}
}
}
}