Advertisement
a1ananth

java1

Oct 24th, 2011
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.42 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. class Car {
  4.     private static final int CAPACITY = 50;
  5.     private static double gasLeft = CAPACITY;
  6.    
  7.     public static void drive(int distance) throws OutOfGasException {
  8.         if (distance > gasLeft) throw new OutOfGasException("You ran out of gas!");
  9.         else {
  10.             gasLeft -= distance;
  11.             System.out.println("You drove " + distance + " miles.");
  12.             System.out.println("You have " + gasLeft + " gallons left in your tank.");
  13.         }
  14.     }
  15.    
  16.     public static void refill(double amount) throws OverflowException {
  17.         if ( (gasLeft + amount) > CAPACITY ) throw new OverflowException("Tank capcity exceeded!");
  18.         else {
  19.             gasLeft += amount;
  20.             System.out.println("You filled your tank with " + amount + " gallons.");
  21.             System.out.println("You have " + gasLeft + " gallons left in your tank.");
  22.         }
  23.     }
  24.    
  25.     public static void main(String[] args) {
  26.         Scanner scanner = new Scanner(System.in);
  27.         System.out.println("\nWelcome to the Car Driving Program.\n");
  28.        
  29.         while(true) {
  30.             System.out.print("\nHow far do you plan to drive? ");
  31.             int distance = scanner.nextInt();
  32.            
  33.             try {
  34.                 drive(distance);
  35.             } catch (OutOfGasException oe) {
  36.                 System.out.println(oe.getMessage());
  37.             }
  38.            
  39.             System.out.print("\nHow much gas did you add? ");
  40.             double amount = scanner.nextDouble();
  41.            
  42.             try {
  43.                 refill(amount);
  44.             } catch (OverflowException oe) {
  45.                 System.out.println(oe.getMessage());
  46.             }
  47.         }
  48.     }
  49. }
  50.  
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement