使用 switch case 生成計算器的 Java 程式


以下程式接受兩個整數 變數,獲取一個關於運算的運算子。根據選定的 運算子,程式執行相應的運算並輸出結果。

示例

import java.util.Scanner;
public class ab39_CalculatorUsingSwitch {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter value of 1st number ::");
      int a = sc.nextInt();

      System.out.println("Enter value of 2nd number ::");
      int b = sc.nextInt();

      System.out.println("Select operation");
      System.out.println("Addition-a: Subtraction-s: Multiplication-m: Division-d: ");
      char ch = sc.next().charAt(0);
      switch(ch) {
         case 'a' :
         System.out.println("Sum of the given two numbers: "+(a+b));
         break;
         case 's' :
         System.out.println("Difference between the two numbers: "+(a-b));
         break;
         case 'm' :
         System.out.println("Product of the two numbers: "+(a*b));
         case 'd' :
         System.out.println("Result of the division: "+(a/b));
         break;
         default :
         System.out.println("Invalid grade");
      }
   }
}

輸出

Enter value of 1st number ::
52
Enter value of 2nd number ::
85
Select operation
Addition-a: Subtraction-s: Multiplication-m: Division-d:
a
Sum of the given two numbers: 137

更新於: 21-6 月-2024

13k+ 次閱讀

開啟你的 職業生涯

透過完成課程,獲得認證

入門
廣告
© . All rights reserved.