24526

Unable to get total to decrease

Question:

I'm currently working on this pretty challenging program that I'm having a hard time understanding. I've gotten pretty far with it but I'm having trouble getting the amount of candy to decrease after each loop. How would I get each pot of candy to decrease along with the total amount? Thank you for your help!

import java.util.Random; public class TreatHouse { int candyPot1; // # of candy in pot 1 int candyPot2; // # of candy in pot 2 int currentPot; // 1 or 2 int candyPot; int totalCandy; int currentTreaters; int treatsPerTreater; public TreatHouse(int candyPot, int totalCandy) { // ints variable currentPot by parameter candyPot, prints message if(candyPot !=1 && candyPot !=2) { //candyPot = 1; currentPot = 1; System.out.println("Invalid input, we will use candy pot 1 first."); } //ensures total # of candy is more than zero if(totalCandy <= 0){ this.totalCandy = 0; System.out.println("We can't give out candy if we don't have any. " +"\nI think we have some from last year. Yep, we have 100 pieces " +"\nof candy to give out."); }else this.totalCandy = totalCandy; // splits the candy between the pots this.totalCandy = this.totalCandy + 100; candyPot1 = this.totalCandy/2; candyPot2 = this.totalCandy - candyPot1; } public int getCandyCount() { return candyPot1 + candyPot2; } public void passOutCandy() { /*if there are enough treats per treater for the given amount per treater, pass out candy from the current pot else display a messagethat the treaters have been tricked (No candy!) but don't change the current pot*/ if(currentPot == 1) { if (treatsPerTreater*currentTreaters <= candyPot1) { candyPot1 = candyPot1 - (treatsPerTreater*currentTreaters); } else { System.out.println("Sorry you've been tricked! No treats for you..."); } currentPot = 2; } else if (currentPot == 2){ if (treatsPerTreater*currentTreaters <= candyPot2) { candyPot2 = candyPot2 - (treatsPerTreater*currentTreaters); } else{ System.out.println("Sorry you've been tricked! No treats for you..."); } currentPot = 1; } } // Sets the # of trick or treaters public void knockKnock() { Random gen = new Random(System.currentTimeMillis()); this.currentTreaters = gen.nextInt(13)+1; // 1 to 13 treaters } // Displays how much candy in each pot, total candy left public void getCandyStatus() { System.out.println("We have " +this.candyPot1+ " pieces of candy left in pot 1 and " + this.candyPot2 + " pieces of candy left in pot 2."); System.out.println("There's a total of " + (this.totalCandy) + " pieces of candy in the two pots."); } //returns the pot number for which candy was last given public int getLastPot() { return candyPot; } public void setTreatsPerTreater(int treatsPerTreater) { treatsPerTreater = currentTreaters*2; } }

Here's the driver program:

import java.util.Scanner; public class Halloween { public static void main (String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Which candy should we give out first? Candy from pot 1 or pot 2?"); int candyPot = scan.nextInt(); System.out.println("How much candy did we buy?"); int totalCandy = scan.nextInt(); TreatHouse ourHouse = new TreatHouse(candyPot, totalCandy); while(ourHouse.getCandyCount()>0) { ourHouse.getCandyStatus(); System.out.println("How much candy per treater should we give out?"); int treatsPerTreater = scan.nextInt(); ourHouse.setTreatsPerTreater(treatsPerTreater); System.out.println("Knock, knock..." + "Trick or treat!!"); ourHouse.knockKnock(); ourHouse.passOutCandy(); } System.out.println("Time to turn off the lights and go to bed!"); System.out.println("The last candy came from pot number " +ourHouse.getLastPot()); System.out.println("Happy Halloween!"); scan.close(); } }

Answer1:

Hint - get rid of this.totalCandy - you don't need it after the constructor is finished, all candy has been divided into the pots.

Keeping the total in a separate variable is needless since you can compute it from candy amount in each pot - in fact having the same number (total candy) represented in two ways (as totalCandy and as a sum of candy in all pots) makes the program harder to write correctly and harder to maintain; and in your case it is indeed the cause of the problem. This advice is also known as <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow">Don't Repeat Yourself principle</a>.

Answer2:

I suspect the problem is here

public void setTreatsPerTreater(int treatsPerTreater) { treatsPerTreater = currentTreaters*2; }

Here you are not using the param passed. currentTreaters is 0, which will lead to treatsPerTreater being 0 as well. So when you call ourHouse.passOutCandy();, `values of pot 1 and 2 dont change.

Answer3:

The only place where you might be going wrong(as far as I can tell) is here,

public void setTreatsPerTreater(int treatsPerTreater) { treatsPerTreater = currentTreaters*2; }

Here, when you modify treatsPerTreater you are changing the local variable treatsPerTreater and not the class variable.

Maybe you meant to say,

public void setTreatsPerTreater(int treatsPerTreater) { this.treatsPerTreater = treatsPerTreater; }

This is called shadowing.

<blockquote>

Some declarations may be shadowed in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity.

</blockquote>

Please read <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.4.1" rel="nofollow">this</a> for more details.<br /> Also have a look at <a href="https://stackoverflow.com/a/33550513/4042839" rel="nofollow">Jiri Tousek's answer</a>

Recommend

  • split with no argument in perl
  • stray characters coming after splitting the list in tcl
  • Mule testing best practices and functional vs unit
  • what does Tilde image mean in MATLAB?
  • How to token a word which combined by two words without whitespace
  • groupby in pandas with different functions for different columns
  • Order By Split Column
  • Creating a DropDownList
  • Who propagate bugfixes across branches (corporate development)?
  • Scrapy recursive link crawler
  • Linq Objects Group By & Sum
  • Deselecting radio buttons while keeping the View Model in synch
  • Javascript simulate pressing enter in input box
  • How reduce the height of an mschart by breaking up the y-axis
  • How to add date and time under each post in guestbook in google app engine
  • SSO with signing and signature validation doesn't work
  • How to show dropdown in excel using jrxml (jasper api)?
  • Importing jscolor library in angular 2
  • Release, debug version and Authorization Google?
  • Websockets service method fails during R startup
  • Alternatives to the OPTIONAL fallback SPARQL pattern?
  • How to get next/previous record number?
  • Apache 2.4 - remove | delete | uninstall
  • Proper way to use connect-multiparty with express.js?
  • Trying to get generic when generic is not available
  • embed rChart in Markdown
  • How to get Windows thread pool to call class member function?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • Django query for large number of relationships
  • costura.fody for a dll that references another dll
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Observable and ngFor in Angular 2
  • How can I use `wmic` in a Windows PE script?
  • failed to connect to specific WiFi in android programmatically
  • UserPrincipal.Current returns apppool on IIS
  • java string with new operator and a literal
  • How to push additional view controllers onto NavigationController but keep the TabBar?
  • How can I use threading to 'tick' a timer to be accessed by other threads?