Java簡單實現:兩個數間的加減乘除


package com.chachan53.method;<details>

import java.util.Scanner;

public class Caculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("請輸入兩個數間的計算,數字和運算符之間用回車分離");
        double n1 = scanner.nextDouble();
        String c = scanner.next();
        double n2 = scanner.nextDouble();
        switch(c){
            case "+"://c的類型是String類型,因此需要使用雙引號""
                System.out.println(n1+"+"+n2+"="+add(n1,n2));
                break;
            case "-":
                System.out.println(n1+"-"+n2+"="+minus(n1,n2));
                break;
            case "*":
                System.out.println(n1+"*"+n2+"="+multiply(n1,n2));
                break;
            //在除法中判斷除數是否為0
            case "/":
                if(n2==0){
                    System.out.println("除數不允許為0!");
                    break;
                }
                System.out.println(n1+"/"+n2+"="+divide(n1,n2));
                break;
            default:
                System.out.println("未定義的方法");
        }
    }
    //定義加減乘除的方法
    public static double add(double n1,double n2){
        return n1+n2;
    }
    public static double minus(double n1,double n2){
        return n1-n2;
    }
    public static double multiply(double n1,double n2){
        return n1*n2;
    }
    public static double divide(double n1,double n2){
        return n1/n2;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM