java设置计算器实现加减乘除清零求平方
时间: 2023-07-07 18:08:44 浏览: 103
以下是一个简单的 Java 计算器程序,实现了加减乘除、清零和求平方功能:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double num1, num2, result;
char operator;
while (true) {
System.out.print("请输入第一个数:");
num1 = input.nextDouble();
System.out.print("请输入操作符(+、-、*、/、s):");
operator = input.next().charAt(0);
if (operator == 's') {
result = num1 * num1;
System.out.println(num1 + " 的平方是 " + result);
continue;
}
System.out.print("请输入第二个数:");
num2 = input.nextDouble();
switch (operator) {
case '+':
result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + result);
break;
case '-':
result = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + result);
break;
case '*':
result = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + result);
break;
case '/':
if (num2 == 0) {
System.out.println("除数不能为0,请重新输入。");
continue;
}
result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);
break;
default:
System.out.println("操作符输入错误,请重新输入。");
continue;
}
System.out.print("是否清零(y/n)?");
char choice = input.next().charAt(0);
if (choice == 'y') {
break;
}
}
input.close();
}
}
```
运行程序后,用户可以按照提示输入两个数字和操作符,然后计算器就会输出结果。如果输入的操作符是 `s`,则计算器会求出第一个数的平方。如果用户输入 `y`,则程序会退出,否则会继续进行下一次计算。
阅读全文