0

I came across this code example on another website. I've been looking at it for a while, trying to figure out something simple, but I'm having difficulty determining where to start. How would I allow a user to enter into the console to turn the light or the fan on/off? All this stuff with setters/getters is confusing. Writing the logic of turning something on/off seems simple, but mix it in with constructors and setters/getters and I get lost. I'm failing to understand how and where to manipulate the isOn boolean with user input.

I'd appreciate any guidance or code. Thanks

public class Household {

   public String choice;//instance variables
   public boolean isOn;

   //constructor
   Household(String choice,boolean isOn) {
       this.isOn=isOn;
       this.choice=choice;
   }

   //methods
   public String getChoice() {
       return choice;
   }

   public void setChoice(String choice) {
       this.choice = choice;
   }

   public boolean isOn() {
       return isOn;
   }

   public void setOn(boolean isOn) {
       this.isOn = isOn;
   }

   public String toString() {
       return "Choice:" + getChoice() + "\tisOn:" + (isOn() ? "Yes" : "NO");
   }

   public static void main(String[] args) {

       Household hh=new Household("toaster", true);
       System.out.println(hh);
       hh=new Household("fan", false);
       System.out.println(hh);
   }
}
Florian Genser
  • 160
  • 2
  • 7
bnr32jason
  • 113
  • 1
  • 11
  • 5
    If "all this stuff" put together is complicated to you, you're going too fast. Split the class to its atomic components, then add a constructor a understand how it works, add a field and understand how it works, and so on. – Luigi Cortese Sep 16 '15 at 16:15
  • @LuigiCortese I've learned about each concept individually, and put together some simple ones of my own, even with user input modifying different aspects. But in this specific program I'm having difficulty. I'm trying to learn from others, perhaps I'm going about it the wrong way. I've read about setters/getters, watched videos about them on YouTube and think I have a good understanding, but this one specifically is throwing me off. – bnr32jason Sep 16 '15 at 16:18
  • If you got methods, variables, constructors, setters and getters... well, that's nothing easier than this example. Try asking something more specific – Luigi Cortese Sep 16 '15 at 16:20
  • The boolean value `isOn` can be modified through the method `setOn` for every instance of `Household`. Is that a start? – Jyr Sep 16 '15 at 16:22
  • I'm going to upload an answer with a few images to help describe these concepts. Give me a few more minutes. :) –  Sep 16 '15 at 16:40
  • I'm not sure how setters/getters can be confusing. A setter sets a variable to something and a getter gets the variable for you. – takendarkk Sep 16 '15 at 17:05
  • @Takendarkk it's not setters and getters themselves that are confusing to me, it's integrating them into the code that is confusing. I understand what they are and what they do. But when it comes to manipulating them using other areas of the code, user input for example, I get lost. – bnr32jason Sep 16 '15 at 17:10
  • @Psychrom I would really appreciate that. Thanks! – bnr32jason Sep 16 '15 at 17:10
  • Sorry bout the wait, I got distracted at work. –  Sep 16 '15 at 17:35
  • It probably doesn't matter much for beginners, but you should know that typically if you're creating getters and setters for specific fields, those fields should be marked as `private` and not `public`. This is so that users of your class don't have direct access to the variable and instead are only allowed to modify it based on the access rules of the getter/setter. – Mage Xy Sep 16 '15 at 17:54
  • if you have a setter and a getter, then does the public/private part really matter? :) You're still going to get or set it regardless. I could see the point of doing that if you only had one or the other, so you could only set it or only get it. –  Sep 16 '15 at 17:57

3 Answers3

3

You can think of a constructor as like a blueprint.

no In the above picture, we have the class in the dotted box. This is the "blueprint." It's not an actual object yet, it just represents how objects should look. In the solid box is an actual object.

The constructor takes the blueprint and actually builds something from it.

   Household(String choice,boolean isOn) {
   this.isOn=isOn;
   this.choice=choice;
   }

Here, we're defining how that blueprint works. In order to build a household object, we need to supply it with a string "choice" and a boolean "isOn". Once we have those two things, we can create a Household object.

Now, you can't turn on the lights in your house before they're built. Once you have a Household object, you'll also have your choice and isOn fields. Say I want to turn off whatever is in the house. enter image description here

Using your code, we have a household named hh, a toaster, and an on/off switch. If you wanted to turn off the on/off switch, you'd use the setter:

    public void setOn(boolean isOn) {
    this.isOn = isOn;
    }

The setter then sets the value of the isOn field on the hh object, as seen in the above picture.

If you wanted to know whether that switch was true or false (on or off), you'd ask:

hh.getOn();

This returns a boolean value, the same value as the isOn field on the object.

You can see this when you call

System.out.println(hh.getOn());

This prints out true or false, depending on whether or not it's set to true or false.

That's how setters and getters work: the setter sets the value of that field, and the getter gets the value of the field.


Now for the (more) fun part.

Since you want to input data, rather than simply outputting data, we have to do something different.

Say I want to have a user type into the console "off" and have it set the households on/off switch to off.

System.out.println(hh); <-- only prints out to console

We need a new object to handle input. Scanner is commonly used for teaching beginners, so we'll use that.

Scanner s = new Scanner(System.in);

This reads data from the system's input stream. You can read about Scanner here.

Now, scanner reads data in as a string using nextLine(); So we'll use that.

String test = s.nextLine();

And of course now we need to test if that string is the same as "off", and if it is, set the isOn field to false (off).

if(test.equals("off") || test.equals("OFF")){
hh.setOn(false);
}

I won't go into more details on how to do the rest of this, such as checking input, looping, etc.

The logic should be in the main method in this application. Wherever you need to modify the household object is where you need to call those setter/getter methods. The constructor is only ever called when you need a brand new object. If this is still confusing, compare the constructor to setting up a game of monopoly. You initially set up the monopoly board, give everyone their money and starting properties, etc. This is all done so that you can actually play the game. When you lose a property in the game, you would use a setter to remove that property. When you need to see how much money, you'd use a getter.

MonopolyPlayer{
int cash;
MonopolyPlayer(){
    cash = 1500; 
    //we're setting this player up to play the game
}


setCash(int i); //now the player has a new amount of cash
getCash(); // he's checking his account
....etc.
}

And so on.

0

How would I allow a user to enter into the console to turn the light or the fan on/off?

Using your code, you could do something like this.

public static void main(String[] args) {
    System.out.println("Enter On or Off for fan: ");
    Scanner scanner = new Scanner(System.in);
    String input = scanner.nextLine();
    boolean on = false;
    if(input.equalsIgnoreCase("yes")) {
       on = true;
    } else if( input.equalsIgnoreCase("no")) {
       on = false;
    } else {
       System.out.println("Please enter yes or no!");
       return;
    }

    Household fan=new Household("fan", on);
    System.out.println(hh);
}

But this isn't really using your setters or getters. You could create your household class like this,

public class Household {

    private String choice;//instance variables
    private boolean isOn;

    public void setOn(boolean isOn) {
        this.isOn = isOn;
    }

    public boolean getOn() {
        return isOn;
    }

    public void setChoice(String choice) {
        this.choice = choice;
    }

    public String getChoice() {
        return choice;
    }

    public String toString() {
       return "Choice:" + getChoice() + "\tisOn:" + (isOn() ? "Yes" : "NO");
    }
}

And in my code above switch it to:

Household fan = new Household();
fan.setChoice("fan");
fan.setOn(on);
System.out.println(fan);
Florian Genser
  • 160
  • 2
  • 7
Austin
  • 4,801
  • 6
  • 34
  • 54
  • Yeah, I can write the logic fine for the on/off code, but utilizing the setters/getters along with that code is what is confusing to me. I'm seeing what I can do right now with your code suggestions, thanks. – bnr32jason Sep 16 '15 at 17:22
0

So to try and break it down.

The idea behind getters and setters is to be able to retrieve and set data on variables inside an object, without having to expose the variables themselves. This means that the fields you have at the top of your class should be declared private. You only want to be able to access them through getters and setters.

In your main method you create an instance of the Household object by using the constructor (you can think of the constructor as the thing which constructs the instance). Your constructor says that to call it, it needs two pieces of data, a String and a boolean. When the constructor is called with these two pieces of data it then stores them in the instance it creates in the fields choice and isOn.

Now that you have your instance of Household (hh), you have an object which contains two pieces of data. If you want to retrieve the data you have stored for one of the variables, you use the getter.

hh.getChoice();

or

hh.isOn();

This will return you the data stored in the choice/isOn field for that specific instance of Household.

If you want to change the data you have stored in hh, you use the setters. So to change the value if isOn you would use

hh.setOn(true);

or

hh.setOn(false);
Kialandei
  • 394
  • 1
  • 11