Code example 5-1 import java.util.Scanner; import java.text.NumberFormat; public class WeightConverter { public sta

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

Code example 5-1 import java.util.Scanner; import java.text.NumberFormat; public class WeightConverter { public sta

Post by answerhappygod »

Code example 5-1import java.util.Scanner;import java.text.NumberFormat;public class WeightConverter { public static void main(String[] args) { Scanner sc = newScanner(System.in); String prompt = "Enterweight 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\nequals\n" + nf.format(weightInKilos) + " kgs\n"; 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 -1 at the firstconsole prompt, what does the code do?
Question 12 options:
figures the weight in kilograms
catches an exception
displays an error message from the getDouble() method
displays an error message from the main() method
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply