Java:整数的算数运算

2024-11-18 09:46:08
推荐回答(2个)
回答(1):

写好了,这是源文件,放到默认包里运行即可

回答(2):

public static void main(String[] args) {
System.out.println("请输入一个计算碰槐式:");
Scanner sr = new Scanner(System.in);
String reg = sr.nextLine();
compute(reg.trim());
sr.close();
}

private static void compute(String regex){
int index = -1;
if ((index = regex.indexOf("+"笑升友)) > 0) {
try {
double firstNum = Double.parseDouble(regex.substring(0, index).trim());
double secondNum = Double.parseDouble(regex.substring(index + 1).trim());
System.out.println(regex + " = " +(firstNum + secondNum));
} catch (NumberFormatException e) {
System.err.println("表达式错误!"笑物);
}
}else if((index = regex.indexOf("-")) > 0){
try {
double firstNum = Double.parseDouble(regex.substring(0, index));
double secondNum = Double.parseDouble(regex.substring(index + 1));
System.out.print(regex + " = " +(firstNum - secondNum));
} catch (NumberFormatException e) {
System.err.println("表达式错误!");
}
}else if((index = regex.indexOf("*")) > 0){
try {
double firstNum = Double.parseDouble(regex.substring(0, index));
double secondNum = Double.parseDouble(regex.substring(index + 1));
System.out.print(regex + " = " +(firstNum * secondNum));
} catch (NumberFormatException e) {
System.err.println("表达式错误!");
}
}else if((index = regex.indexOf("/")) > 0){
try {
double firstNum = Double.parseDouble(regex.substring(0, index));
double secondNum = Double.parseDouble(regex.substring(index + 1));
System.out.print(regex + " = " +(firstNum / secondNum));
} catch (NumberFormatException e) {
System.err.println("表达式错误!");
}
}

}
这样可以吧