Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- class Car {
- private static final int CAPACITY = 50;
- private static double gasLeft = CAPACITY;
- public static void drive(int distance) throws OutOfGasException {
- if (distance > gasLeft) throw new OutOfGasException("You ran out of gas!");
- else {
- gasLeft -= distance;
- System.out.println("You drove " + distance + " miles.");
- System.out.println("You have " + gasLeft + " gallons left in your tank.");
- }
- }
- public static void refill(double amount) throws OverflowException {
- if ( (gasLeft + amount) > CAPACITY ) throw new OverflowException("Tank capcity exceeded!");
- else {
- gasLeft += amount;
- System.out.println("You filled your tank with " + amount + " gallons.");
- System.out.println("You have " + gasLeft + " gallons left in your tank.");
- }
- }
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- System.out.println("\nWelcome to the Car Driving Program.\n");
- while(true) {
- System.out.print("\nHow far do you plan to drive? ");
- int distance = scanner.nextInt();
- try {
- drive(distance);
- } catch (OutOfGasException oe) {
- System.out.println(oe.getMessage());
- }
- System.out.print("\nHow much gas did you add? ");
- double amount = scanner.nextDouble();
- try {
- refill(amount);
- } catch (OverflowException oe) {
- System.out.println(oe.getMessage());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement