javaSE練習--運算子和條件結構

憤怒的阿木木發表於2020-12-20

將四則運算器和麵積運算器合二為一,作一個運算器,主選單讓使用者選擇是做四則運算還是面積運算,分為兩個子選單,讓使用者選擇加減乘除或者形狀。如下介面:
在這裡插入圖片描述
**加粗樣式
**


```java

```java
import java.util.Scanner;

public class ALU {
    static Scanner input = new Scanner(System.in);
    public static void calculate(){ //四則運算
        System.out.println("1.加法");
        System.out.println("2.減法");
        System.out.println("3.乘法");
        System.out.println("4.除法");
        int n = input.nextInt();
        int x ;
        int y;
        switch (n){
            case 1:
                System.out.println("請輸入兩個運算數:");
                 x = input.nextInt();
                 y = input.nextInt();
                System.out.println(x+y);
                break;
            case 2:
                System.out.println("請輸入兩個運算數:");
                 x = input.nextInt();
                 y = input.nextInt();
                System.out.println(x-y);
                break;
            case 3:
                System.out.println("請輸入兩個運算數:");
                x = input.nextInt();
                y = input.nextInt();
                System.out.println(x*y);
                break;
            case 4:
                System.out.println("請輸入兩個運算數:");
                x = input.nextInt();
                y = input.nextInt();
                System.out.println(x/y);
                break;
        }
    }
    public static void calculateArea(){ //運算面積
        System.out.println("1.三角形");
        System.out.println("2.正方形");
        System.out.println("3.矩形");
        System.out.println("4.圓形");
        int n = input.nextInt();
        int x ;
        int y;
        switch (n){
            case 1:
                System.out.println("請輸入三角形的底和高");
                x = input.nextInt();
                y = input.nextInt();
                System.out.println((x*y)/2);
            case 2:
                System.out.println("請輸入正方形的邊長");
                x = input.nextInt();
                System.out.println((x*x));
            case 3:
                System.out.println("請輸入矩形的長和寬");
                x = input.nextInt();
                y = input.nextInt();
                System.out.println((x*y));
            case 4:
                System.out.println("請輸入圓的半徑");
                x = input.nextInt();
                System.out.println(3.14*Math.pow(x,2));
        }
    }
    public static void main(String[] args) {
        System.out.println("請輸入運算種類:\n1.四則運算:\n2.計算面積:");
        int n = input.nextInt();
        if(n == 1) calculate();
        else if(n == 2) calculateArea();
    }
}

相關文章