以下是一个简单的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();
}
}
此代码通过用户输入两个数和运算符,然后根据运算符执行相应的运算,最终输出结果。您可以根据自己的需求对此代码进行修改和扩展。