以下是一個(gè)簡(jiǎn)單的Java計(jì)算器代碼示例:
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();
}
}
此代碼通過(guò)用戶輸入兩個(gè)數(shù)和運(yùn)算符,然后根據(jù)運(yùn)算符執(zhí)行相應(yīng)的運(yùn)算,最終輸出結(jié)果。您可以根據(jù)自己的需求對(duì)此代碼進(jìn)行修改和擴(kuò)展。