View Full Version : Problem with boolean value being changed without being told to

11-15-2010, 01:44 AM
Hello everyone!
I'm currently doing an assignment which involves a snack machine. I'm currently working on the PacketOfCrisp class. It needs to start with 10 crisps, and have a boolean field for whether or not it's closed. This field is called open and is obviously set to false when the object is created. It also needs to give out some messages, ie if the packet is not open then a message should appear saying that the packet is closed. If the pack has no crisps left a message should appear saying as such. Other than that when selecting eatCrisp the amount of crisps in the packet should go down by one. Here is what I have so far:

public void eatCrisp()
if(open = false) {
System.out.println("Open packet");
else if (open = true && numOfCrisps >= 1) {
numOfCrisps = numOfCrisps - 1;
else {
System.out.println("No Crisps!");

Now for some reason when I invoke eatCrisp it takes out a crisp and changes the "open" field of the object to true and I can't figure out why. As far as I can figure it should be giving me a message of "Open packet" until I open the packet with the "openPacket" method, but instead "eatCrisp" is doing that by itself.

Any ideas?

Logic Ali
11-15-2010, 02:36 AM
if(open = false) { // Here you're setting it to false
System.out.println("Open packet");
else if (open = true && numOfCrisps >= 1) //Here you're setting it to true

Learn your operators. Also try executing a visual string comparison between the name of the language you're supposed to be studying and the title of this forum.

11-15-2010, 02:40 AM
This forum is for Java is it not?
So what do I need to put in the brackets then to make my if statements work? I mean, it works fine if I'm just using something like:

if(cost >= 20) {
System.out.println etc etc

but it's not working with the code I posted above.

11-15-2010, 02:41 AM
Wait, sorry, my mistake. This is for javascript.
Sorry to bother you lot!