Advertisement
richarduie

SpeedConverter.java

Apr 3rd, 2013
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. import java.util.InputMismatchException;
  2. import java.util.Scanner;
  3.  
  4.  
  5. public class SpeedConverter
  6. {
  7. // only need one conversion factor - use it to
  8. // multiply for KPH to MPH - divide for M to K
  9. public static final double CONVERSION = 0.62137;
  10.  
  11. public static void main( String[] args ) {
  12. // use a single scanner to collect input
  13. Scanner scan = new Scanner( System.in );
  14. // get boolean that indicates whether the direction
  15. // of the conversion is to be from KPH to MPH
  16. Boolean isToMph = getConvertDirection( scan );
  17. if (null == isToMph) return; // exit for bad input
  18. // get speed input
  19. Double speed = getSpeedInput( scan );
  20. if (null == speed) return; // exit for bad input
  21.  
  22. // advise user of results
  23. report( speed, isToMph );
  24.  
  25. // NOTE: Boolean and Double wrappers were employed to permit
  26. // null returns to indicate input exceptions to caller, since
  27. // exceptions were handled in input methods. The principle is
  28. // stated as "Input and Validation are the same step."
  29. }
  30.  
  31. public static Boolean getConvertDirection( Scanner scan ) {
  32. Boolean isToMph = null; // default for bad input
  33. System.out.println(
  34. "Which conversion do you want?\n" +
  35. "(for KPH to MPH, enter 1 - for MPH to KPH, enter 2)"
  36. );
  37. try {
  38. isToMph = 1 == scan.nextInt();
  39. }
  40. catch ( InputMismatchException e ) {
  41. System.out.println(
  42. "Invalid input for conversion direction - must be either\n" +
  43. "1 for KPH to MPH -OR- 2 for MPH to KPH."
  44. );
  45. }
  46. return isToMph;
  47. }
  48. public static Double getSpeedInput( Scanner scan ) {
  49. Double speed = null; // default speed for bad input
  50. System.out.println(
  51. "What speed value do you want converted?\n"
  52. );
  53. try {
  54. speed = scan.nextDouble();
  55. }
  56. catch ( InputMismatchException e ) {
  57. System.out.println(
  58. "Invalid input for speed - must be numeric."
  59. );
  60. }
  61. return speed;
  62. }
  63. public static double convert(double speed, boolean isToMph) {
  64. return isToMph ? speed * CONVERSION : speed / CONVERSION;
  65. }
  66. public static void report( double speed, boolean isToMph ) {
  67. System.out.println(
  68. "the speed of " + speed + (isToMph ? " KPH" : " MPH") +
  69. " is equivalent to " + convert( speed, isToMph ) +
  70. speed + (isToMph ? " MPH" : " KPH")
  71. );
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement