题解 | #简单计算器#

简单计算器

http://www.nowcoder.com/practice/b8f770674ba7468bb0a0efcc2aa3a239

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String str = scan.next();

        char opera = '0';
        int indexs = -1; //如果下标为-1 则输入的运算符没有加减乘除
        for(int i = 0; i < str.length(); i++) {
            switch(str.charAt(i)) {
                case '+': indexs = i; opera = '+';
                    break;
                case '-': indexs = i; opera = '-';
                    break;
                case '*': indexs = i; opera = '*';
                    break;
                case '/': indexs = i; opera = '/';
                    break;
            }
        }
        if(indexs == -1) {
            System.out.println("Invalid operation!");
        } else {
            String zfx1 = str.substring(0, indexs);
            String zfx2 = str.substring(indexs + 1, str.length());
            double x1 = Double.parseDouble(zfx1);
            double x2 = Double.parseDouble(zfx2);
            switch(opera) {
                case '+': System.out.printf("%.4f+%.4f=%.4f", x1, x2, (x1 + x2));
                    break;
                case '-': System.out.printf("%.4f-%.4f=%.4f", x1, x2, (x1 - x2));
                    break;
                case '*': System.out.printf("%.4f*%.4f=%.4f", x1, x2, (x1 * x2));
                    break;
                case '/':if(x2 == 0) {
                    System.out.println("Wrong!Division by zero!");
                } else {
                    System.out.printf("%.4f/%.4f=%.4f", x1, x2, (x1 / x2));
                }
            }
        }
    }
}
Java基础练习题 文章被收录于专栏

都是一些基础的语法题目,每天可以刷几道。

全部评论

相关推荐

某牛奶:一觉醒来全球程序员能力下降200%,小伙成功scanf惊呆在座个人。
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务