Java中,输入一个数学表达式,如:1+2,然后输出计算后的结果:1+2=3。

2024-12-04 18:09:59
推荐回答(4个)
回答1:


这样应该就可以了

回答2:

//算式
public static void test32() throws Exception{
    System.out.println("请输入算式:");
    Scanner scanner = new Scanner(System.in);
    String str = scanner.next("-?\\d*\\.?\\d+[+-/*]-?\\d*\\.?\\d+");
    String[] xyStr = str.split("[+-/*]");
    float x = Float.parseFloat(xyStr[0]);
    float y = Float.parseFloat(xyStr[1]);
    float r = 0;
    char opt = '+';
    if(str.contains("+")){
        opt = '+';
        r = x + y;
    }else if(str.contains("-")){
        opt = '-';
        r = x - y;
    }else if(str.contains("*")){
        opt = '*';
        r = x * y;
    }else if(str.contains("/")){
        opt = '/';
        r = x / y;
    }
    System.out.println(x+""+opt+y+"="+r);
}

回答3:

import java.util.Scanner;

public class test1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个数学表达式,如'1+1'、'1-1'、'1*1'、'1/1'");
String str = sc.next();
if(str.contains("+")){
String[] num = str.split("+");
double num1 = Double.parseDouble(num[0]);
double num2 = Double.parseDouble(num[1]);
System.out.println("运算结果是:"+num1+"+"+num2+"="+(num1+num2));
}else if(str.contains("-")){
String[] num = str.split("-");
double num1 = Double.parseDouble(num[0]);
double num2 = Double.parseDouble(num[1]);
System.out.println("运算结果是:"+num1+"-"+num2+"="+(num1-num2));
}else if(str.contains("*")){
String[] num = str.split("\\*");
double num1 = Double.parseDouble(num[0]);
double num2 = Double.parseDouble(num[1]);
System.out.println("运算结果是:"+num1+"*"+num2+"="+(num1*num2));
}else{
String[] num = str.split("/");
double num1 = Double.parseDouble(num[0]);
double num2 = Double.parseDouble(num[1]);
System.out.println("运算结果是:"+num1+"/"+num2+"="+(num1/num2));
}
}

回答4:

import java.util.Scanner;

public class Test1 {

    public static void main(String[] args) {
        //读取控制台输入数据
        Scanner sc = new Scanner(System.in); 
        String readLine = sc.nextLine();
        //定义字符串组进行运算
        String[] str;
        //判断输入的是什么关系
        if(readLine.contains("+")){
             str = readLine.split("\\+");
             System.out.println(str[0]+"+"+str[2]+"="+String.valueOf(Long.parseLong(str[0])+Long.parseLong(str[1])));
        };
        if(readLine.contains("-")){
             str = readLine.split("\\-");
             System.out.println(str[0]+"-"+str[2]+"="+ String.valueOf(Long.parseLong(str[0])-Long.parseLong(str[1])));
        };
        if(readLine.contains("*")){
            str = readLine.split("\\*");
             str = readLine.split(str[0]+"*"+str[2]+"="+ String.valueOf(Long.parseLong(str[0])*Long.parseLong(str[1])));
        };
        if(readLine.contains("÷")){
             str = readLine.split("\\÷");
             str = readLine.split(str[0]+"÷"+str[2]+"="+ String.valueOf(Long.parseLong(str[0])/Long.parseLong(str[1])));
        };
        
    }
}