java實(shí)現(xiàn)計(jì)算器的代碼怎么寫

小億
116
2023-08-10 22:08:26
欄目: 編程語言

以下是一個(gè)簡(jiǎn)單的Java代碼實(shí)現(xiàn)計(jì)算器的示例:

import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("請(qǐng)輸入第一個(gè)數(shù)字:");
double num1 = scanner.nextDouble();
System.out.println("請(qǐng)輸入第二個(gè)數(shù)字:");
double num2 = scanner.nextDouble();
System.out.println("請(qǐng)選擇操作:");
System.out.println("1. 加法");
System.out.println("2. 減法");
System.out.println("3. 乘法");
System.out.println("4. 除法");
int operation = scanner.nextInt();
double result = 0;
switch(operation) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
case 3:
result = num1 * num2;
break;
case 4:
result = num1 / num2;
break;
default:
System.out.println("無效的操作");
return;
}
System.out.println("結(jié)果:" + result);
}
}

該代碼實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的計(jì)算器,用戶可以輸入兩個(gè)數(shù)字和操作,程序根據(jù)用戶選擇的操作進(jìn)行相應(yīng)的計(jì)算,并輸出結(jié)果。

0