Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.InputMismatchException;
- import java.util.Scanner;
- public class SpeedConverter
- {
- // only need one conversion factor - use it to
- // multiply for KPH to MPH - divide for M to K
- public static final double CONVERSION = 0.62137;
- public static void main( String[] args ) {
- // use a single scanner to collect input
- Scanner scan = new Scanner( System.in );
- // get boolean that indicates whether the direction
- // of the conversion is to be from KPH to MPH
- Boolean isToMph = getConvertDirection( scan );
- if (null == isToMph) return; // exit for bad input
- // get speed input
- Double speed = getSpeedInput( scan );
- if (null == speed) return; // exit for bad input
- // advise user of results
- report( speed, isToMph );
- // NOTE: Boolean and Double wrappers were employed to permit
- // null returns to indicate input exceptions to caller, since
- // exceptions were handled in input methods. The principle is
- // stated as "Input and Validation are the same step."
- }
- public static Boolean getConvertDirection( Scanner scan ) {
- Boolean isToMph = null; // default for bad input
- System.out.println(
- "Which conversion do you want?\n" +
- "(for KPH to MPH, enter 1 - for MPH to KPH, enter 2)"
- );
- try {
- isToMph = 1 == scan.nextInt();
- }
- catch ( InputMismatchException e ) {
- System.out.println(
- "Invalid input for conversion direction - must be either\n" +
- "1 for KPH to MPH -OR- 2 for MPH to KPH."
- );
- }
- return isToMph;
- }
- public static Double getSpeedInput( Scanner scan ) {
- Double speed = null; // default speed for bad input
- System.out.println(
- "What speed value do you want converted?\n"
- );
- try {
- speed = scan.nextDouble();
- }
- catch ( InputMismatchException e ) {
- System.out.println(
- "Invalid input for speed - must be numeric."
- );
- }
- return speed;
- }
- public static double convert(double speed, boolean isToMph) {
- return isToMph ? speed * CONVERSION : speed / CONVERSION;
- }
- public static void report( double speed, boolean isToMph ) {
- System.out.println(
- "the speed of " + speed + (isToMph ? " KPH" : " MPH") +
- " is equivalent to " + convert( speed, isToMph ) +
- speed + (isToMph ? " MPH" : " KPH")
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement