使用Java设计一款简单的计算器(加、减、乘,除,平方、立方)
时间: 2023-07-04 21:03:39 浏览: 133
以下是一个简单的计算器的Java代码示例,支持加、减、乘、除、平方和立方运算:
```
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double num1, num2, result;
int choice;
System.out.print("Enter first number: ");
num1 = input.nextDouble();
System.out.print("Enter second number: ");
num2 = input.nextDouble();
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Square");
System.out.println("6. Cube");
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice) {
case 1:
result = num1 + num2;
System.out.println("Result: " + result);
break;
case 2:
result = num1 - num2;
System.out.println("Result: " + result);
break;
case 3:
result = num1 * num2;
System.out.println("Result: " + result);
break;
case 4:
if (num2 == 0) {
System.out.println("Error: Division by zero");
} else {
result = num1 / num2;
System.out.println("Result: " + result);
}
break;
case 5:
result = num1 * num1;
System.out.println("Result: " + result);
break;
case 6:
result = num1 * num1 * num1;
System.out.println("Result: " + result);
break;
default:
System.out.println("Invalid choice");
break;
}
}
}
```
使用时,用户输入两个数字和运算选项,程序根据选项进行相应的计算,并输出结果。
阅读全文