Java输入取值的时候好难啊,就用了判断取值,另外转化的时候不能用float,要用double,不然精度会受影响。

import java.io.IOException;
import java.util.Scanner;

/*
简单计算器
 */
public class _54_SimpleCalculator {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            //整体输入,判断得到a、b数组
            String str = sc.nextLine();
            char[] chars = str.toCharArray();
            char[] a1 = new char[chars.length];
            char[] b1 = new char[chars.length];
            int n = 0;
            char ch = 0;
            for (int i = 0; i < chars.length; i++) {
                if (chars[i] >= '0' && chars[i] <= '9') {
                    a1[i] = chars[i];
                } else if (chars[i] == '.'){
                    a1[i] = chars[i];
                }else {
                    ch = chars[i];
                    n = i;
                    break;
                }
            }
            for (int i = n+1; i < chars.length; i++) {
                b1[i] = chars[i];
            }

            //得到a、b
            String stra = String.valueOf(a1);
            double a = Double.parseDouble(stra);
            String strb = String.valueOf(b1);
            double b = Double.parseDouble(strb);

            //计算
            if (ch == '+') {
                System.out.printf("%.4f+%.4f=%.4f", a, b, a + b);
            } else if (ch == '-') {
                System.out.printf("%.4f-%.4f=%.4f", a, b, a - b);
            } else if (ch == '*') {
                System.out.printf("%.4f*%.4f=%.4f", a, b, a * b);
            } else if (ch == '/') {
                if (b == 0) {
                    System.out.printf("Wrong!Division by zero!");
                } else {
                    System.out.printf("%.4f/%.4f=%.4f", a, b, a / b);
                }
            } else {
                System.out.printf("Invalid operation!");
            }
            System.out.println();
        }
        sc.close();
    }
}