【发布时间】:2019-05-19 01:36:38
【问题描述】:
代码:
import java.util.Scanner;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class MPGAppBigDecimal
{
public static void main(String[] args)
{
System.out.println("Welcome to the Miles Per Gallon Calculator.");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// get the miles driven from the user
System.out.print("Enter miles driven: ");
String milesString = sc.next();
// get the gallons of gas used
System.out.print("Enter gallons of gas used: ");
String gallonsString = sc.next();
// calculating miles per gallons
BigDecimal miles = new BigDecimal(milesString);
BigDecimal gallons = new BigDecimal(gallonsString);
BigDecimal mpg = miles.divide(gallons).setScale(2, RoundingMode.HALF_UP);
// display the result
System.out.println("Miles per gallon is " + mpg.toString() + ".");
System.out.println();
// see if the user wants to continue
System.out.print("Calculate another MPG? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
当我输入十进制值时,它会引发异常: 线程“主”java.lang.ArithmeticException 中的异常:非终止十进制扩展;没有精确可表示的十进制结果。
【问题讨论】:
-
你提供什么输入?
标签: java