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

2012/11/13

Help: Writing loops (do,for,while) to find a value above 99.

vivbala vivbala

2012/11/13

#
Hello guys, This is my first post on the greenfoot forum. I would like help how on to find a value above 99 that is an array of integers using loops.
Zamoht Zamoht

2012/11/13

#
To find all the values above 99 or just the first one that appears?
vivbala vivbala

2012/11/13

#
Just the one after.
Zamoht Zamoht

2012/11/13

#
I'm not that sure what you want to do, but try this loop.
for (int i = 0; i < 150; i++)
{
     int whatEver = whatEverArray[i];
     if (whatEver > 99)
     {
          //write here what you want to do with whatEver (which is above 99)
          i = 150; //or return or break or whatever you want to stop the loop
     }
}
Now I don't know anything about your code so the names are pretty random, but remember that "for (int i = 0; i < 150; i++)" will keep running up to 150 if it doesn't find a value above 99. This will give you an error if there isn't 150 integers stored in your array. (What I'm trying to say is change that number to whatever fits your program)
vivbala vivbala

2012/11/13

#
Great! Thanks you very much, this has helped a lot. I just have one more question about arrays. What is the array used for? And what integers am I suppose to put in there?
Zamoht Zamoht

2012/11/13

#
It's used if you have a collection of values. I used it in one of my scenarios for exp needed to next level.
int expToLevel [] = {20, 50, 100, 180, 250, 340, 500};
        level = 1;

        int e = exp;
        int temp = 0;
        while (e >= 0 && level != 8)
        {
            temp = e;
            e -= expToLevel[level - 1];

            if (e >= 0)
            {
                level++;
            }
        }
So here the code continues to check if there is enough exp to go to a new level. This is one example, but i use arrays aswell to create coordinates like.
int objectAtCoordinate[][];
Then at a specific coordinate you can add a value and then the world will later on look at that coordinate to check if there is an object. If you want more objects at one coordinate you can use int objectAtCoordinate, so the first one is x, the second y and the last one z. This coordinate usage might seem a bit useless since Greenfoot worlds already have coordinates they can use. I really hope this helped.
danpost danpost

2012/11/13

#
Check out the Java tutorials, especially the sections concerning loops and arrays. This is the link for control flow statements (for, while, and do). This is the link for arrays.
You need to login to post a reply.