Results 1 to 17 of 17
  1. #1
    gnng is offline Member
    Join Date
    Mar 2011
    Location
    San Diego, CA
    Posts
    34
    Rep Power
    0

    Default Need Serious Help on Odometer exercise

    First off, yes, this is homework so I am not asking anyone to do it for me. I am taking an online Java class (not recommended!) where the only resource is the Savitch "Absolute Java" book. I have read the book and reread it 50 times now and cannot figure this out. Can someone point me in the right direction?

    Here is the problem - you've probably seen it before.

    "Define a class called Odometer that will be used to track fuel and mileage for an auto- mobile. The class should have member variables to track the miles driven and the fuel efficiency of the vehicle in miles per gallon. Include a mutator function to reset the odometer to zero miles, a mutator function to set the fuel efficiency, a mutator function that accepts miles driven for a trip and adds it to the odometer's total, and an accessor method that returns the number of gallons of gasoline that the vehicle has consumed since the odometer was last reset."

    A few stupid questions:

    1) Am I writing a separate program to create the class called Odometer and then a second program that accesses the class? I ask because the book video series goes into hiding information by using private and public classes.

    2) Can someone simply explain the concept of Mutator and Accessor?

    Thanks for any help you can give me.

    Gary

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    I'm all out of serious. How about some frivolous help instead? ;)

    Java Code:
    class Foo {
        private String text;
    
        Foo (String t) {
            text = t;
        }
    
        public void setText(String newText) {
            // Mutator: changes the value
            text = newText;
        }
    
        public String getText() {
            // Accessor: give access to private member variables
            return text;
        }
    }
    
    class Bar {
        public static void main(String[] args) {
            Foo f = new Foo("Hello World");
            System.out.println(f.getText());
            f.setText("Goodbye, Farewell and Amen");
            System.out.println(f.getText());
        }
    }

  3. #3
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Junky gave you an example and I will do some basic explanations, A mutator changes the value of some instance value(setter) and an accessory reads an instance variable(getter).

    They usually take the form of
    Java Code:
    getSomeVariableInClass()
     And
    setSomeVariableInClass()
    I recommend picking up headfirst java and reading it. Also, check out the sun java tutorials.

    As junky has shown, every class can have a main and inmthis case you should do all the testing in main. There is no reason to split this into multiple files.

  4. #4
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    Why have Mutator methods? So you can control the value of the variable.
    Java Code:
    class Foo {
        int variableWithPositiveValue;
    
        public void setValue(int value) {
            if(value > 0) {
                variableWithPositiveValue = value;
            }
        }
    
        public int getValue() {
            return variableWithPositiveValue;
        }
    }
    
    class Bar {
        public static void main(String[] args) {
            Foo f = new Foo();
            f.setValue(9);
            System.out.println(f.getValue()); // output is 9
            f.setValue(-100); // no change
            System.out.println(f.getValue()); // output is 9
            f.variableWithPositiveValue = -100;
            System.out.println(f.getValue()); // output is -100 OOOPS!
        }
    }

  5. #5
    gnng is offline Member
    Join Date
    Mar 2011
    Location
    San Diego, CA
    Posts
    34
    Rep Power
    0

    Default

    First off, thanks for the fast response. Can I explain what I think is happening and have you comment?

    1. In this first part you are creating a private class called "Foo" and stating that the text is "T". This is the original value.

    class Foo {
    private String text;

    Foo (String t) {
    text = t;
    }

    2. In this next part, you're saying that though the private value of the text is "T", you want to allow it to be changed to something else.

    public void setText(String newText) {
    // Mutator: changes the value
    text = newText;
    }

    3. Not sure what this actually is doing.

    public String getText() {
    // Accessor: give access to private member variables
    return text;
    }

    4. I guess this confused me too.

    class Bar {
    public static void main(String[] args) {
    Foo f = new Foo("Hello World");
    System.out.println(f.getText());
    f.setText("Goodbye, Farewell and Amen");
    System.out.println(f.getText());

    Thank you for your patience - I am just not grasping this. I am running an A in this class halfway through but I have hit a wall with this concept.

  6. #6
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    Close, however; it's actually a bit different, the class foo actually has package access(default) the string named text is a private variable of the class Foo.

    You understand the setter correctly, it let's you modify(write) the instance variable.

    The getter is the accessor, it provides you with a way to view the classes instance variables.

    Finally, Bar is just another class with only a main method that tests Foo.

  7. #7
    gnng is offline Member
    Join Date
    Mar 2011
    Location
    San Diego, CA
    Posts
    34
    Rep Power
    0

    Default

    Why do you use this:
    Foo f = new Foo("Hello World");
    System.out.println(f.getText());

    And then use this:
    f.setText("Goodbye, Farewell and Amen");
    System.out.println(f.getText());

    I understand what they are doing, just not why they are different.

  8. #8
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    Have you compiled and run the code to see what the output is? comments are about the line of code above.

    Java Code:
    Foo f = new Foo("Hello World");
    // This creates a Foo object and passes "Hello World" to the constructor which sets
    // text to be "Hello World".
    System.out.println(f.getText());
    // the getText method "gets" the value stored in the text variable which is "Hello World"
    // This is then passed to the println method which displays it.
    f.setText("Goodbye, Farewell and Amen");
    // The String "Goodbye, Farewell and Amen" is passed to the setText method which
    // changes the value of the text variable.
    System.out.println(f.getText());
    // Does the same as above only now the value of text is "Goodbye, Farewell and Amen"
    // and this is what is displayed instead of "Hello World"

  9. #9
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    In the first one junky uses a constructor which takes a string and sets the instance variable when the object is created, he prints the value to show the value of the string is what you expect it to be.

    In the next section he uses a setter to change the instance variable, then prints it to show it was successful.

    I suggest you read up about constructors in the sun tutorials.

    Edit: too slow :(

  10. #10
    gnng is offline Member
    Join Date
    Mar 2011
    Location
    San Diego, CA
    Posts
    34
    Rep Power
    0

    Default

    Thank you very much! I will definitely read up on this. Learning java from reading a textbook with no instructor interaction is about as hard as anything I have ever done - maybe harder. It might be easier to just build a space shuttle in my garage :-)

  11. #11
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    If you get a good book its not too bad. I suggest getting head first java for the good explanations and java software solutions for a book with lots of exercises(haven't gotten to read software solutiOns yet but I scanned the exercises and liked them. )

  12. #12
    donkatec is offline Member
    Join Date
    Mar 2011
    Posts
    3
    Rep Power
    0

    Default

    Quote Originally Posted by gnng View Post
    Why do you use this:
    Foo f = new Foo("Hello World");
    System.out.println(f.getText());

    And then use this:
    f.setText("Goodbye, Farewell and Amen");
    System.out.println(f.getText());

    I understand what they are doing, just not why they are different.
    Let me try in simplest terms, gnng.

    Line 1 is the constructor. It is creating an object called "f". It will have "Hello World" in it. Whenever your demo program needs to do something to this f object, it must first start of with "f." Like f.getText, or f.setText.

    If you understand about methods, whenever it has the word return, it will return a value, which is why they are usually called getters (accessors). When you change/set something it is a mutator, like setText.

  13. #13
    gnng is offline Member
    Join Date
    Mar 2011
    Location
    San Diego, CA
    Posts
    34
    Rep Power
    0

    Default

    OK, thank you. I am seriously not usually this dense but this is really hard reading a chapter and then having to do programming, especially when some of the material is in the next chapter. For example, we haven't even covered constuctor yet. I'll work on this tomorrow and post my code if I can crack it.

  14. #14
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    I typed up a post on my phone and lost it because of a misclick, how annoying ><

    Now to retype on a computer.

    Check out the book head first java, you can probably find it used on amazon for 15-20 books, it's a fun, easy read, and it's only about 700 pages. It doesn't cover everything and some of the topics it does cover(threads, to name one) aren't very lengthy explanations. Considering this book is designed for beginners it makes sense to not delve too deeply into the harder to understand topics.

    The book took me approximately 3 weeks while reading at work, and I thoroughly enjoyed it and highly recommend it to any beginners. After reading this book you should be able to ace any intro to java class.

    Finally, if you are finished with this thread please mark it solved with the thread tools at the top.

  15. #15
    gnng is offline Member
    Join Date
    Mar 2011
    Location
    San Diego, CA
    Posts
    34
    Rep Power
    0

    Default still stuck after over 18 hours

    Guys, I think my problem with this problem is that if requires me to know things that we have not covered yet. For example, it says in the instructions to use mutators and accessors but that isn't covered until next week - ahhh, the joys of online classes. Anyway, I am stuck on the basics on how to even put this together. Could I walk through this in simple terms and have you give me advice?

    Part 1: Define the class
    Here is where I will define all the variables private class, such as milesDriven and milesPerGallon. Do I set their values to 0 here as well?

    Part 2: Do I need a constructor? I read that this would be where I would store the formulas? So one formula I need is (gallonsUsed = milesDriven / milesPerGallon) - speaking of which, does that mean I need define gallonsUsed in the first part?

    Part 3: Mutator - to change the value? So if the original value of miles is O, the mutator allows me to change that value? This is the "setter"?

    Part 4: Accesor: This is the "return" piece? Is that always formatted like that?

    Part 5: Create a new class that will access the Odometer class.

    Now here is where I get really stuck. I need to:

    a. Ask user to enter miles
    b. Allow them to reset the odometer to 0 (not even sure why they want this)
    c. Ask user for mpg
    d. Compute gallons used

    If anyone can walk me through this and first tell me if I am going at this the right way and then give me hints on how to write this code, I would be very appreciative.

    Thanks,

    Gary

    PS: Please be patient - I've spoken with other students who are equally stuck on this. The teacher is gone on Spring Break but this is due during the break and all the tutors are gone so we are left stranded. I have watched tons of OOP videos and read lots of website tutorials but it's left me more confused than ever.:eek:

  16. #16
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    We are here to help, so we will of course be patient.

    Lets start by breaking down how to build a class, once you understand how to, we can worry about actually building it.

    A real class should have certain methods, which represent behavior. It should also have instance variables, which represent state. Try to think about it in real life products, for instance, a TV has state and behavior.

    In a TV the state can be the volumes current setting, the current channel, and all the things that can be set through the settings menu.

    The behavior does things like display the channel at the current sound, change the channel, change the volume, etc.

    Your problem actually models a real world item, an odometer on a car definitely has state and behaviour.

    state:
    Java Code:
    total miles driven
    mpg
    miles on a trip
    behavior:
    Java Code:
    reset the total,
    compute mpg
    reset current trip
    reset total
    Now that we have that covered, you need to create an instance variable in the class for each piece of state you want the odometer to have.

    In the tv class you would have the below representation of state
    Java Code:
    public class TV{
      private int channel;    //these represent the state
      private int volume;     //of the tv, things like channel
      private int[] settings; //volume, and settings
    }
    The reason for the private modifiers is to encapsulate the state so not anything can access it. For example, you may not want someone to put the tv to a negative volume or channel.

    To manipulate these variables you create setters(mutators) and getters(accessors)

    These do not need to be used in the class, they are used in main, or other classes.

    When defining setters and getters you create one per state variable(generally)

    Java Code:
    public class TV{
      //instance variables
      public void setChannel(int channel){
        if(channel > 0){
          this.channel = channel;
        }
        else{
          System.out.println("Not a correct channel");
        }
      }
      //all the other setters will be similar
      public int getChannel(){
        return channel;
      }
      //all the other getters will be similar
    }
    Once you provided getters and setters you gave a way for other classes to read and write your class(odometer in your case) TV.

    Now, lets do some discussion on how a constructor constructor works.

    all constructors have similar form
    Java Code:
    public ClassName(args)
    
    or
    
    public TV(int channel, int volume, int[] settings)
    You can have multiple constructors which take different arguments but all do similar things. You can also change the access modifier to private, protected, or package access.

    Here is the constructors for TV

    Java Code:
    public class TV{
      //instance variables
      public TV(){//this is a default constructor, takes no arguments
        channel = 0;   //it just sets the variables to there default(null for 
        volume = 0;    //objects 0 otherwise)
        settings = null;
      }  
      public TV(int channel){
        this.channel = channel;
        volume = 0;
        settings = null;
      }
      //more constructors to take other argument types
    }
    Now that we have designed the constructors, getters, setters, and instance variables, we want to move into designing behavior for the class.

    In the case of the tv, it has things like display channel, change channel, and change settings, so lets create them.

    Java Code:
    public class TV{
      //instance variables
      //constructors
      //getters and setters
      public void displayChannel(){
        //code to manipulate the tv's hardware
      }
      public void changeChannel(int channel){
        this.channel = channel;
        displayChannel();
      }
      public void changeVolume(int volume){
        this.volume = volume;
        displayChannel();
      }
      //other similar methods
    }
    This should give you a pretty solid way to begin creating your class, using this, try your best to implement instance variables, constructors, getters, setters, and methods, then post the code.

  17. #17
    gnng is offline Member
    Join Date
    Mar 2011
    Location
    San Diego, CA
    Posts
    34
    Rep Power
    0

    Default

    Thanks, this helped a lot. I also went into the lab and it was verified that the teacher is having us do things that we haven't covered, which is why this has been so difficult. On to the next project!

Similar Threads

  1. Codechef exercise
    By sunde887 in forum New To Java
    Replies: 8
    Last Post: 01-24-2011, 07:47 PM
  2. Have I done this exercise right?
    By ccie007 in forum New To Java
    Replies: 7
    Last Post: 09-28-2010, 05:54 PM
  3. Exercise for java 3d
    By armiri in forum Java Software
    Replies: 3
    Last Post: 05-13-2010, 11:13 PM
  4. I/O exercise
    By Feldom in forum New To Java
    Replies: 1
    Last Post: 10-28-2007, 04:48 PM
  5. help with exercise
    By e_as're in forum New To Java
    Replies: 3
    Last Post: 09-25-2007, 10:14 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •