输入数学表达式并计算出结果(包括小数)
萨达斯
要求如下:
/**
* 输入一个数学计算表达式,如:1+2
* 然后输出计算后的结果:1+2=3
* 这里计算表达式只计算一次即可,可以使用加减乘除任意一个,可以进行小数运算。
*/
代码如下:
public class Test07 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入算式:");
String input = scan.nextLine();//接收数据
int index = -1;
if((index=input.indexOf("+"))>0){//加法运算
double[] result=check(input,index);
// double num1 = Double.parseDouble(input.substring(0, index));
// double num2 = Double.parseDouble(input.substring(index+1));
System.out.println(input + "=" + (result[0]+result[1]));
}else if((index=input.indexOf("-"))>0){//减法运算
double[] result=check(input,index);
// double num1 = Double.parseDouble(input.substring(0, index));
// double num2 = Double.parseDouble(input.substring(index+1));
System.out.println(input + "=" + (result[0]-result[1]));
}else if((index=input.indexOf("*"))>0){//减法运算
double[] result=check(input,index);
// double num1 = Double.parseDouble(input.substring(0, index));
// double num2 = Double.parseDouble(input.substring(index+1));
System.out.println(input + "=" + (result[0]*result[1]));
}else if((index=input.indexOf("/"))>0){//减法运算
double[] result=check(input,index);
// double num1 = Double.parseDouble(input.substring(0, index));
// double num2 = Double.parseDouble(input.substring(index+1));
if(result[1] == 0){
System.out.println("除数为0,输入错误");
}else{
System.out.println(input + "=" + (result[0]/result[1]));
}
}
}
//可以封装方法
public static double[] check(String input,int index){
double[] result = new double[2];
result[0] = Double.parseDouble(input.substring(0,index));
result[1] = Double.parseDouble(input.substring(index+1));
return result;
}
}
输出结果为:
请输入算式:
2.5/2.6
2.5/2.6=0.9615384615384615