Code:
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();
}
}
}
When I am inputting decimal value it is throwing an exception: Exception in thread "main" java.lang.ArithmeticException: Non terminating decimal expansion; no exact representable decimal result.