以下是一個簡單的Java計算器代碼示例:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.println("Enter the second number: ");
double num2 = scanner.nextDouble();
System.out.println("Enter the operation (+, -, *, /): ");
char operation = scanner.next().charAt(0);
double result = 0;
switch(operation) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("Invalid operation.");
}
System.out.println("Result: " + result);
scanner.close();
}
}
此代碼通過用戶輸入兩個數和運算符,然后根據運算符執行相應的運算,最終輸出結果。您可以根據自己的需求對此代碼進行修改和擴展。