142k views
1 vote
Code example 5-1 import java.util.Scanner; import java.text.NumberFormat; public class WeightConverter { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String prompt = "Enter weight in lbs: "; boolean isValid = false; double weightInPounds = 0.0; while (!isValid) { weightInPounds = getDouble(sc, prompt); if (weightInPounds > 0) { isValid = true; } else { System.out.println("Weight must be greater than 0."); } } double weightInKilos = weightInPounds / 2.2; NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(2); String message = weightInPounds + " lbs\\equals\\" + nf.format(weightInKilos) + " kgs\\"; System.out.print(message); } public static double getDouble(Scanner sc, String prompt) { double d = 0.0; boolean isValid = false; while (!isValid) { System.out.print(prompt); if (sc.hasNextDouble()) { d = sc.nextDouble(); isValid = true; } else { System.out.println ("Error! Invalid decimal value. Try again."); } sc.nextLine(); } return d; } } (Refer to code example 5-1.) If the user enters "two hundred" at the console prompt, what does the code do? a. displays an error message from the main() method b. displays an error message from the getDouble() method c. figures the weight in kilograms d. throws an InputMismatchException

1 Answer

3 votes

Answer:

It displays an error message from the getDouble() method

Step-by-step explanation:

The above would be the result because of the following

1. Variable d is declared as a double variable and should be used as such.

2. The getDouble() method is also defined to handle double variables only.

When the program tries to accept at

weightInPounds = getDouble(sc, prompt);

The getDouble method is called immediately and since the value

"two hundred" entered in string, it can't handle this data type and it (the getDouble method) will display an error message

User Mayday
by
4.3k points