做一个简易计算器,用户输入两个数,实现加减乘除

package com.xiong.dan;
import java.util.Scanner;
public class calculator2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        double a=0,b=0;
        System.out.println("请输入第一个数:");
        if(scanner.hasNextDouble()){
            a= scanner.nextDouble();
        }
        else{
            System.out.println("错误!");
        }
        System.out.println("请输入第二个数:");
        if(scanner.hasNextDouble()){
            b= scanner.nextDouble();
        }
        else{
            System.out.println("错误!");
        }
        System.out.println("请输入+-*/:");
        String sign =scanner.next();
        switch (sign){
            case "+":
                add(a,b);
                break;
            case "-":
                jian(a,b);
                break;
            case "*":
                cheng(a,b);
                break;
            case "/":
                chu(a,b);
                break;
            default:
                System.out.println("输入错误!");
                break;


        }
        scanner.close();

    }
    public static void add(double a,double b){
        double sum=a+b;
        System.out.println(a+"+"+b+"="+sum);
    }
    public static void jian(double a,double b){
        double sum=a-b;
        System.out.println(a+"-"+b+"="+sum);
    }
    public static void cheng(double a,double b){
        double sum=a*b;
        System.out.println(a+"*"+b+"="+sum);
    }
    public static void chu(double a,double b){
        double sum=a/b;
        if(b==0){
            System.out.println("除数不能为0!");
        }
        else{
            System.out.println(a+"/"+b+"="+sum);
            }

    }

}

你可能感兴趣的:(java)