Need Help with Accessor and Mutator Methods

Printable View

• February 9th, 2011, 04:41 AM
ankur_032
Need Help with Accessor and Mutator Methods
I am working on a vehicle program which enables vehicle to drive and fill up the vehicle's tank from fuel station.
Here is the code:
Code :

```/* * To change this template, choose Tools | Templates * and open the template in the editor. */       package carapplication;   import java.util.Scanner;     class FuelStation{ static double fuel;   public void setfuel(double fuel){ FuelStation.fuel=fuel;   } public static Vehicle fillup(Vehicle c){ c.setfuel(c.getfuel()+10); return c; }     }     class FuelOverFlowException extends Exception {   }   class OutOfFuelException extends Exception {   }       class Vehicle { double fuel=10;   public double getfuel(){ return fuel; }     public void drive(double km) {   if (fuel < 0) { try { throw new OutOfFuelException(); } catch (OutOfFuelException ex) {   } }   else if (fuel > 60) { try { throw new FuelOverFlowException(); } catch (FuelOverFlowException ex) {   } } }   public void setfuel(double fuel){ this.fuel=fuel;     }   } class Car extends Vehicle{     }     /** * * @author Ankur */ public class Main { static double fuel;   /** * @param args the command line arguments */ public static void main(String [] args){   Scanner input = new Scanner (System.in); // TODO code application logic here FuelStation audi = new FuelStation();   for (;;){ System.out.println("M for Display this Menu."+"\n"+"F for displaying current litres of fuel"+"\n"+"X for Filling Up the Vehicle With X litres"+"\n"+"D for Driving the Car"); String ch = input.next();   if (ch.equalsIgnoreCase("X")) { System.out.println("Enter Desired amount of fuel"); fuel = input.nextDouble(); audi.setfuel(fuel);   } else if (ch.equalsIgnoreCase("F")){ System.out.println("You have "+fuel+"litres left"); }   }   } }```

I have some problem with mutator method, It does changes the value of fuel but its does not add to the previous value. Any suggestion how can I do this?
• February 9th, 2011, 09:00 AM
copeg
Re: Need Help with Accessor and Mutator Methods
Quote:

I have some problem with mutator method, It does changes the value of fuel but its does not add to the previous value.
What do you mean by 'it' and add to the previous value? More importantly, when you run the program with a certain input, how do you expect it to behave and how does it actually behave?