Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Nov 2010
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Problem with boolean value being changed without being told to

    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:

    Code:
    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?

  • #2
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    Quote Originally Posted by JoshuaDBoyd View Post
    Code:
    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.

  • #3
    New to the CF scene
    Join Date
    Nov 2010
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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.

  • #4
    New to the CF scene
    Join Date
    Nov 2010
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Wait, sorry, my mistake. This is for javascript.
    Sorry to bother you lot!


  •  

    Posting Permissions

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