user1932739 user1932739 - 16 days ago 4
Java Question

Java beginner: classes and methods

I'm a noob and Java is my first programming language.
I've this problem that I'm trying to solve:


Define a class to represent a Sugar Bowl sugar characterized by three
things: total capacity (in grams), available quantity and quantity of
the spoon (how many grams of sugar takes the spoon associated with
it). Set in this class:


  1. A constructor method to create a sugar bowl.

  2. A method that allows to know the amount of sugar in the sugar bowl.

  3. A method that allows to know how much it takes a spoonful of sugar.

  4. A method which, given a number of scoops, removes the corresponding amount of sugar, returning this value.

  5. A method to add sugar. If the supplied value exceeds the available space, the sugar bowl should be full, and the remaining amount
    returned. In other cases, should return zero.



Set the class
RunSugarBowl
as main and play around.



public class SugarBowl {

private int totalCapacity;
private int availableSpace;
private int spoonSize;
private int occupiedSpace = totalCapacity-availableSpace;//is the same as amount of sugar in the bowl.

SugarBowl (int totalCapacity){
availableSpace=totalCapacity;
spoonSize = totalCapacity/20;//arbitrary size
}

public int spoon(){
return spoonSize;
}

public int occupied(){
return occupiedSpace;
}

public void scoops (int numberOfScoops){
int amountTaken = numberOfScoops * spoonSize;
if (amountTaken<=occupiedSpace){
occupiedSpace=occupiedSpace-amountTaken;
System.out.println(amountTaken);}
else{
System.out.println("There's not that amount of sugar in the sugar bowl. Try less.");}
}
public int addSugar (int addedAmount){
if (addedAmount>availableSpace){
int remainingAmount=addedAmount-availableSpace;
availableSpace=0;
occupiedSpace = totalCapacity-availableSpace;
return remainingAmount;}
else{
availableSpace = availableSpace - addedAmount;
occupiedSpace = totalCapacity-availableSpace;
return 0;}
}
}


My problem now is that my
one.occupied
method returns
0
instead off the
200
in:



public class RunSugarBowl {
public static void main(String[] args) {
SugarBowl one = new SugarBowl(200);
one.addSugar(300);
System.out.println("Occupied size is : "+ one.occupied());
}
}

ARC ARC
Answer

First off, just as a tip, it's useful to add method headers so you know what your method is trying to do. Aka, if you look at your specifications many of your methods require you to "know how much..." so the methods should return a number rather than immediately printing something out (I made the same mistake when I began coding).

You are printing out those numbers within your methods (which is useful for debugging, but not what your finished product should do). You can return an int and then print out that integer in your RunSugarBowl (see below).

I've given you a general framework of what that entails and added some comments that may help you. You've done well to begin with. If you have more problems, just ask in a comment.

public class SugarBowl {
    private int totalCapacity;
    private int availableSpace;
    private int spoonSize;
    private int occupiedSpace;//starts at 0, because there's nothing in the bowl.

    /**
     * Constructor for the sugar bowl.
     * @param totalCapacity     The total capacity of the bowl.
     */
    public SugarBowl (int totalCapacity){
        this.totalCapacity = totalCapacity; //set the totalCapacity for the bowl
        availableSpace=totalCapacity;
        spoonSize = totalCapacity/20;//arbitrary size
        occupiedSpace = 0;
    }
    /**
     * Shows how much sugar can fit in a spoon.
     * @return  The size of the spoon
     */
    public int spoon(){
        return spoonSize;
    }
    /**
     * Returns amount of sugar in the bowl.
     * @return  The amount of occupied space
     */
    public int occupied(){
        return occupiedSpace;
    }
    /**
     * Removes the amount of sugar based on the
     * number of scoops passed into it.
     * @param numberOfScoops    The number of scoops
     * @return          The amount of sugar removed
     */
    public int scoops (int numberOfScoops){

        int possibleAmountTaken = numberOfScoops * spoonSize;
        int actualAmountTaken = 0;
        //Think about sugar, even if there is less sugar than the spoon size, 
        //can a spoon still remove that amount?
        //aka the only time 0 sugar should be taken is when there is 0 sugar in the bowl
        if (possibleAmountTaken<=occupiedSpace){
            actualAmountTaken = possibleAmountTaken;
        }
        else{
            //there may still be sugar, just not enough for every scoop, you still have to remove it
            //actualAmountTaken = ???
        }
        occupiedSpace = occupiedSpace - actualAmountTaken;
        //what about availableSpace?
        //availableSpace = ???
        return actualAmountTaken;       
    }
    /**
     * Adds the specified amount of sugar to the bowl.
     * 
     * @param addedAmount   The amount of sugar added to the bowl
     * @return  The overflow amount of sugar or 0 if there was no overflow
     */
    public int addSugar (int addedAmount){
        int overflow = 0;
        if (addedAmount>availableSpace){
            overflow = addedAmount-availableSpace;
            //your bowl is going to be full, what happens to occupiedSpace and availableSpace?
            //availableSpace = ???
            //occupiedSpace = ???
        }
        else{
            //overflow is already 0 so you don't have to do anything with it
            //update availableSpace and occupiedSpace
            //availableSpace = ???
            //occupiedSpace = ???
        }
        return overflow;
    }
}

With your above main example:

public class RunSugarBowl {
    public static void main(String[] args) {
        SugarBowl one = new SugarBowl(200);
        System.out.println("Sugar overflow: " + Integer.toString(one.addSugar(300))); //once working correctly should print out 100 for the overflow
        System.out.println("Occupied size is : "+ one.occupied());
    }
}

UPDATE

The reason you would use this.totalCapacity is because of the following lines of code:

public class SugarBowl {
    private int totalCapacity; //totalCapacity for this object; aka this.totalCapacity refers to this variable
    //..

    public SugarBowl (int totalCapacity){ // <-- totalCapacity passed in
        this.totalCapacity = totalCapacity; //this.totalCapacity is setting the totalCapacity for this instance of the object to the value passed in
        //..

Notice how your constructor is being passed in a variable called "totalCapacity" and yet the class also has its own internal variable called totalCapacity. Comparable code without the "this" keyword is as follows:

public class SugarBowl {
    private int bowlTotalCapacity; //totalCapacity for this object
   //..

    public SugarBowl (int totalCapacity){ 
        bowlTotalCapacity = totalCapacity;
        //..

You'd just have to make sure that after you initialize that wherever you would have used totalCapacity before, you'd change it to bowlTotalCapacity. It's just a whole lot easier to use this.totalCapacity to refer to the totalCapacity within this class. Take a look here for more information: http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html.

Technically you don't actually use totalCapacity ever again after you initially construct the object, but if you want to see the weirdness that happens if you don't include the this portion try to understand what happens in the following code:

public class ThisExample {
    private int wrongExample = 0;
    private int thisExample = 0;

    public ThisExample (int wrongExample, int thisExample){
        wrongExample = wrongExample;
        this.thisExample = thisExample; 
    }

    public int getThisExample(){
        return thisExample;
    }
    public int getWrongExample(){
        return wrongExample;
    }
}

Running the following may help you understand better:

public class ThisExampleMain {
    public static void main(String[] args) {
        ThisExample ts = new ThisExample(50, 50);
        //you want this to be 50 but it ends up being 0:
        System.out.println("Wrong: " + ts.getWrongExample());
        //this returns the correct answer:
        System.out.println("Right: " + ts.getThisExample());
    }
}