This site requires JavaScript, please enable it in your browser!
Greenfoot back
Poland
Poland wrote ...

2015/12/2

I have found a serious glitch involving loops

Poland Poland

2015/12/2

#
So this while loop is infinite, but WHY!?! I can't wrap my head around it! It shouldn't even function, but it does, and it should only generate 3 crabs when the operator sign is reversed, but it only EVER makes one. I'm really losing my patience with this.
Super_Hippo Super_Hippo

2015/12/2

#
Poland wrote...
and it should only generate 3 crabs when the operator sign is reversed, but it only EVER makes one.
I think it should create 3 lobsters and not 3 crabs. What do you mean with "when the operator sign is reversed"? You code creates one crab in line 5 and adds it to the world in line 6. You don't create a lobster because you set 'i' to 0 and that is not greater than 3... If you change > to <, it will create one lobsters, because the 'new Lobster()' is outside the loop. The method should look like this:
    private void addLobsters(int numberOfLobsters)
    {
        int i=0;
        while(i < numberOfLobsters){
            i++;
            Lobster myLobster = new Lobster();
            addObject(myLobster, Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber(560));
        }
    }
Or:
    private void addLobsters(int numberOfLobsters)
    {
        for (int=0; i < numberOfLobsters; i++)
        {
            Lobster myLobster = new Lobster();
            addObject(myLobster, Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber(560));
        }
    }
Improvement: Save the crab into a field in the world. When adding a lobster, make sure that this lobster does not spawn in close range of the crab (so the game isn't over in one second).
danpost danpost

2015/12/2

#
Super_Hippo was correct that the initial code would not produce any lobsters because of the condition ' i > 3 '. However, even with ' i < numberOfLobsters ' as the condition, you would only create one lobster. This is because you only create one before the loop and are adding the same one into the same world 3 times (which, of course, can only be done once). The first code-set provided by Super_Hippo shows the creating of lobsters within the loop, thereby creating 'numberOfLobster' lobsters and adding each one into the world.
Super_Hippo Super_Hippo

2015/12/2

#
Mistake in the second one: It should be 'int i=0' and not 'int=0'.
Poland Poland

2015/12/7

#
Thanks, but it was a glitch. I restarted the program and I got it to work. This is what I ended up with:
 public int numberOfLobsters=0;
    public void addLobsters(int lobsters)
    {
        
        for(int j=0; j < lobsters; j++){
            int x=Greenfoot.getRandomNumber(560);
            int y=Greenfoot.getRandomNumber(560);
            addObject(new Lobster(), x, y);
            numberOfLobsters++;
        }
You need to login to post a reply.