//做一个计算器
package homework;
import java.util.Scanner;
public class homework5 {
public static void main(String[] args) {
try {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
System.out.println("计算器");
System.out.println("使用说明 1.加法 2.减法 3.乘法 4.除法");
for (double i = 0; i < 100; i++) {
System.out.print("\n请选择运算规则:");
int num = input.nextInt();
switch (num) {
case 1:
System.out.println("你选择了加法");
System.out.print("请输入第1个加数:");
double jiashu1 = input.nextDouble();
System.out.print("请输入第2个加数:");
double jiashu2 = input.nextDouble();
System.out.println("运算结果为:" + jiashu1 + " + " + jiashu2
+ " = " + (jiashu1 + jiashu2));
break;
case 2:
System.out.println("\n******你选择了减法******\n");
System.out.print("请输入被减数:");
double jianshu1 = input.nextDouble();
System.out.print("请输入减数:");
double jianshu2 = input.nextDouble();
System.out.printf("运算结果为:" + jianshu1 + " - " + jianshu2
+ " = " + (jianshu1 - jianshu2));
break;
case 3:
System.out.println("\n******你选择了乘法******\n");
System.out.print("请输入第1个因数:");
double chengfa1 = input.nextDouble();
System.out.print("请输入第2个因数:");
double chengfa2 = input.nextDouble();
System.out.printf("运算结果为:" + chengfa1 + " * " + chengfa2
+ " = " + (chengfa1 * chengfa2));
break;
default:
System.out.println("\n你的选择错误,请重新选择!");
break;
}
}
} catch (Exception e) {
System.out.print("请输入整数");
}
}
}
思路:
1,使用BigDecimal类里面的valueOf(doeble d)方法,
2,在使用BigDecimal类里面的stripTrailingZeros()方法,去除没用的0,
3,最后把BigDecimal类型转换为字符串,
4,注意,不能在把字符串转换为doule了,在转换为double前面的事情就白做了,
public class Demo11 {