Java實現一個簡易計算器


做一個多功能計算器 ====== 歡迎使用計算器系統 ========

  1. int + int

  2. double + double 、

  3. 計算 n 的階乘

  4. 計算 a的 n次方、

  5. 退出系統、

import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        //計算器界面
        calInter();
        Scanner sc = new Scanner(System.in);
        System.out.println("請輸入功能選項:");
        int i = sc.nextInt();
        int j = 1;
        while(true){
            switch (i){
                case 1:
                    System.out.println("結果為:"+addInt());
                    break;
                case 2:
                    System.out.println("結果為:"+addDouble());
                    break;
                case 3:
                    System.out.println("結果為:"+factor());
                    break;
                case 4:
                    System.out.println("結果為:"+power());
                    break;
                case 5:
                    exit();
                    j = 0;
                    break;
                default:
                    System.out.println("輸入功能選項有誤,您只能選擇1~5之間的整數,請重新輸入!");
            }
            if(j == 0){
                break;
            }
            System.out.println("請輸入功能選項:");
            i = sc.nextInt();
        }
    }
    //計算器界面
    public static void calInter(){
        System.out.println("====== 歡迎使用計算器系統 ========");
        System.out.println("1. int + int");
        System.out.println("2. double + double ");
        System.out.println("3. 計算 n 的階乘");
        System.out.println("4. 計算 a的 n次方");
        System.out.println("5. 退出系統");
    }
    //Int加法
    public static int addInt(){
        Scanner sc = new Scanner(System.in);
        System.out.println("第一個int數為:");
        int a = sc.nextInt();
        System.out.println("第二個int數為:");
        int b = sc.nextInt();
        return a + b;
    }
    //double加法
    public static double addDouble(){
        Scanner sc = new Scanner(System.in);
        System.out.println("第一個double數為:");
        double a = sc.nextDouble();
        System.out.println("第二個數double為:");
        double b = sc.nextDouble();
        return a + b;
    }
    //n的階乘
    public static int factor(){
        Scanner sc = new Scanner(System.in);
        System.out.println("階乘n為:");
        int n = sc.nextInt();
        int fact = 1;
        for(int i = 1; i <= n ;i++){
            fact *= i;
        }
        return fact;
    }
    //a的n次方
    public static double power(){
        Scanner sc = new Scanner(System.in);
        System.out.println("底數a為:");
        int a = sc.nextInt();
        System.out.println("冪數n為:");
        int n = sc.nextInt();
        return Math.pow(a,n);
    }
    //退出系統
    public static void exit(){
        System.out.println("退出系統");
    }


}

 


免責聲明!

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



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