Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: General question on using array inside a nested for loop

  1. #1
    Member
    Join Date
    Mar 2021
    Location
    Ontario, Canada
    Posts
    35
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default General question on using array inside a nested for loop

    Hello everyone,
    For the past couple of weeks, I have been working on a final project for my Java Introduction course. I pretty much have it completed, but since I have a couple of weeks before it is due, I wanted to try and improve upon it and possible get some extra credits. Before I change any code in the program, I thought I would start a basic program to to see if I could get the basic principal to work. To start, here is the code I have been practicing with.
    import java.util.ArrayList;
    import java.util.Random;
     
    public class AnimalArrays {
        int index;
        int sheep = 2;
     
        String xPos;
        String yPos;
        String positions;
        ArrayList<Integer> list = new ArrayList<Integer>(5);
        String[] sheepCreate = new String[sheep];
     
        public static void main(String[] args) {
            AnimalArrays newAnimal = new AnimalArrays();
        }
     
        public AnimalArrays() {
            // creates a list from 1 to 5
            for(int i = 1; i <= 5; i++) {
                list.add(i);
            }
            Random rand = new Random();
            for(int count = 0; count < sheep; count++) {
                // creates a String[] with x and y positions for each sheep
                index = rand.nextInt(list.size());
                xPos = Integer.toString(list.remove(index));
                index = rand.nextInt(list.size());
                yPos = Integer.toString(list.remove(index));
                positions = xPos + "," + yPos;
                sheepCreate[count] = positions;
                System.out.println(positions);
            }
            // removes unused items from the list
            for(int count = 0; count < list.size(); count++) {
                list.remove(count);
            }
     
            startingGrid();
        }
     
        public void startingGrid(){
            // writes the numbers 1-5 along the top
            for (int xValue = 1; xValue < 6; xValue++) {
                System.out.print("  " + xValue);
                } // end of for statement
                     System.out.println("");
     
                // writes the numbers 1-5 down the left side
                for (int yValue = 1; yValue < 6; yValue++) {
                    System.out.print(yValue + " ");
     
                    for (int xValue = 1; xValue < 6; xValue++) {
     
                        //for (int sc = 0; sc < 2; sc++) {
     
                            if (xValue == (Integer.parseInt(String.valueOf(sheepCreate[0].charAt(0)))) && yValue == Integer.parseInt(String.valueOf(sheepCreate[0].charAt(2)))) {
                                System.out.print("S  ");
                            } // end of if statement
                            else
                                System.out.print("*  ");
     
                        //} // end of inner for statement
     
                    }// end of middle for statement
     
                    System.out.println("");
                } // end of outer for statement
     
        } // end of startingGrid method
    }

    You sill see inside the startingGrid method, I have 3 for loops nested together (1 is commented out). As it sits, it prints the grid perfectly with the one sheep("S") in its correct position, however if I uncomment the last for loop, and change the 0 in the sheepCreate[0] to sc to get both sheep to show up, this is were it messes everything up.

    I have been banging my head the entire day trying to understand why. Can anyone give me an explanation on where I went wrong.

    My thought process for the above code is;
    first for loop sets Y to 1
    Second for loop sets X to 1
    third for loop would goes through the the sheep array (2 in total) and compares the 2 values stored to the x and y value, if true, it puts an 'S' there other wise it puts a '*' there.

    as the third loop is done, second loop increases by 1 until it is done then first loop increases by 1 till its done (hopefully that made sense)
    The final product is to have a grid with multiple sheep shown on it.

    Any help you can give will help greatly.

    Thanks

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: General question on using array inside a nested for loop

    Can you post the program's current output with some comments saying what is wrong with it
    and also post what the output should look like?

    Where does the code use an index to look at the contents of the sheepCreate array at different indexes?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Mar 2021
    Location
    Ontario, Canada
    Posts
    35
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: General question on using array inside a nested for loop

    This forum will not allow me to upload any images (click on the manage attachments button and nothing opens to allow an upload) so I will do my best to describe what is going on.

    As currently programmed the output looks like this;
    5,2 <- first set of coordinates taken from the for loop in the AnimalArrays method (this one prints out perfectly the way the code is now)
    3,4 <- second set of coordinates taken from the for loop in the AnimalArrays method
    ...1 2 3 4 5
    1 * * * * *
    2 * * * * S <- location matches the first set of coordinates
    3 * * * * *
    4 * * * * *
    5 * * * * *

    as soon as I uncomment the last nested for loop in the startingGrid method and convert the 0's in the "sheepCreate[0].charAt(0)" to "sc" (the variable in the last FOR loop, sheepCreate[sc].charAt(0)) and rerun it this is what appears;
    2,5
    4,1
    ...1 2 3 4 5
    1 * * * * * * * * * *
    2 * * * * * * * * * *
    3 * * * * * * * * * *
    4 * * * * * * * * * *
    5 * * S S * * * * * *

    You can see that both the 'S' are not in the correct location and also a second grid was drawn right beside it

    what I am trying to make appear is this;
    2,5
    4,1
    ...1 2 3 4 5
    1 * * * S *
    2 * * * * *
    3 * * * * *
    4 * * * * *
    5 * S * * *

    As for the "Where does the code use an index to look at the contents of the sheepCreate array at different indexes?" question, directly in the IF statement,
    if (xValue == (Integer.parseInt(String.valueOf(sheepCreate[0].charAt(0)))) && yValue == Integer.parseInt(String.valueOf(sheepCreate[0].charAt(2))))

    I take the first value and convert it to an INTEGER and compare it to the xValue variable created in the middle FOR loop. Same goes for the second value, but compares it to the yValue.
    I hope this is what you were asking.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: General question on using array inside a nested for loop

    Where does the code use an index to look at the contents of the sheepCreate array at different indexes?" question, directly in the IF statement,
    if (xValue == (Integer.parseInt(String.valueOf(sheepCreate[0].charAt(0)))) && yValue == Integer.parseInt(String.valueOf(sheepCreate[0].charAt(2))))
    That statement only uses the index for the first item [0] in the array. What about the other elements in the array?
    What if there are 5 sheep? What happens then?


    A better OOP approach would be to have a Sheep class with two int values for the x and y values.
    Get rid the the String that has two digits in it that need to be converted to String and back to int.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Mar 2021
    Location
    Ontario, Canada
    Posts
    35
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: General question on using array inside a nested for loop

    In the second example shown, I change the [0] value to [sc] (the last FOR loops control value). This way that value will change every rotation. Currently I have that loop stop at 2 but once I can get this figured out, I will change that to a TotalSheep value, this way if there is 5 sheep, it will stop on 5 or stop on 4 if there are only 4 sheep, and so on.

    As for your last statement, I am not sure I understand correctly. Creating a String[] for each sheep is the only way I can see a variable holding 2 positions, so I convert them to an INT so I am able to compare them to the xValue and yValue locations. If I don't convert them, I get an error "trying to compare a String to an Int." If this is the wrong way of thinking, then I am open to learning the correct way.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: General question on using array inside a nested for loop

    Creating a String[] for each sheep
    I assume you mean that the string array holds Strings, one for each sheep.
    I am suggesting that there be a Sheep class that contains x and y values for each sheep's location.
    The Sheep objects could be held in a Sheep[] array.

    --- Update ---

    In the second example shown, I change the [0] value to [sc]
    Is there a new version of the code that does that?

    The logic for the code could be:
    nested loops that look at each row and the columns in that row
    If there is a sheep at that row,column print "S"
    else print "*"

    The "If there is a sheep at that row,column" logic would be replaced with a method that takes the row, column as arguments and returns true or false based on if there is a sheep at that location.
    The isThereSheepHere(row.column) method would use a loop to search through the Sheep[] array comparing the row, column argument to the contents of the Sheep objects in the array.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Member
    Join Date
    Mar 2021
    Location
    Ontario, Canada
    Posts
    35
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: General question on using array inside a nested for loop

    Is there a new version of the code that does that?
    its in the code given, I just commented out the for loop that controls it and manually changed the [sc] to [0]

    The logic for the code could be:
    nested loops that look at each row and the columns in that row
    If there is a sheep at that row,column print "S"
    else print "*"
    this is what I have been attempting to do with the nested for loops.

    I'm starting to think the way Java (OOP) is written is messed up, seems like to have to write more code than what seems to be necessary. Maybe once I advance more into the course it might start to make sense, but right now it seems that Java wants you to jump around from method to method, class to class to get to the results. A lot of movement when you should be able to use 1 or 2 to get the job done. Then again it could be that I just don't understand all of it yet.

    Anyways, back to your suggestion about creating a sheep class, if I create the sheep class and put the String [] sheepCreate in there, I would still have to convert them to an INT so that they can be used as comparison values, so when the nested for loop run, looking at each individual spot on the grid and comparing them to each sheep, would the outcome not be the same as now.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: General question on using array inside a nested for loop

    creating a sheep class, if I create the sheep class and put the String [] sheepCreate in there
    There would not be any Strings. The x and y values would be stored in the Sheep object as int values, no Strings.

    You will find as programs get larger, that separating the logic into various methods will simplify the code and make it easier to read and understand.
    Nesting for loops three deep makes the code more complicated and delicate and makes changes to it harder.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Mar 2021
    Location
    Ontario, Canada
    Posts
    35
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: General question on using array inside a nested for loop

    There would not be any Strings. The x and y values would be stored in the Sheep object as int values, no Strings.

    You will find as programs get larger, that separating the logic into various methods will simplify the code and make it easier to read and understand.
    Nesting for loops three deep makes the code more complicated and delicate and makes changes to it harder.
    Thanks Norm,
    I will play around with your suggestions and see what I come up with.

  10. #10
    Member
    Join Date
    Mar 2021
    Location
    Ontario, Canada
    Posts
    35
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: General question on using array inside a nested for loop

    Hi Norm,
    Took your advice, and started over, here is the code so far. (no grid on this one, will wait to apply it)
    import java.util.ArrayList;
    import java.util.Random;
     
    public class AnimalArrays {
        int index;
        int sheep = 2;
     
        ArrayList<Integer> list = new ArrayList<Integer>(5);
        String[] sheepCreate = new String[sheep];
     
        public static void main(String[] args) {
            AnimalArrays newAnimal = new AnimalArrays();
        }
     
        public AnimalArrays() {
     
            sheepCreate sheep1 = new sheepCreate();
            sheepCreate sheep2 = new sheepCreate();
     
            // creates a list
            for (int count = 1; count <= 5; count++) {
                list.add(count);
                //sheepNames.add("sheep" + (Integer.toString(count)));
            }
     
            Random rand = new Random();
     
                index = rand.nextInt(list.size());
                sheep1.xValue = list.remove(index);
                index = rand.nextInt(list.size());
                sheep2.xValue = list.remove(index);
                index = rand.nextInt(list.size());
                sheep1.yValue = list.remove(index);
                index = rand.nextInt(list.size());
                sheep2.yValue = list.remove(index);
     
     
            System.out.println(sheep1.xValue + "," + sheep1.yValue);
            System.out.println(sheep2.xValue + "," + sheep2.yValue);
        }
    }
     
    class sheepCreate{
        int xValue;
        int yValue;
     
    }

    This works and assigns the x and y values to the sheep class. Only problem is in this example there are only 2 sheep, so I played around with the following to see if you can create objects of sheepCreate using a loop this way, if the sheep number increases so does sheep objects.

    import java.util.ArrayList;
    import java.util.Random;
     
    public class AnotherAnimalArray {
        int index;
        int sheep = 2;
     
        ArrayList<Integer> list = new ArrayList<Integer>(5);    // creates an ArrayList of numbers , 5 numbers max
        ArrayList<String> sheepNames = new ArrayList<String>();             // creates an ArrayList of sheepNames
     
        public static void main(String[] args) {
            AnotherAnimalArray newAnimal = new AnotherAnimalArray();        // creates a new instance of AnotherAnimalArray
        }
     
        public AnotherAnimalArray() {
     
            // creates a list
            for (int count = 1; count <= 5; count++) {
                list.add(count);                                            // adds the numbers 1-5 to the list ArrayList
                sheepNames.add("sheep" + (Integer.toString(count)));        // adds the names of the sheep1 to Sheep5 to the sheepNames ArrayList
            }
     
            /*
            Is it possible to use the sheepNames values in a loop to create new objects of sheepCreate
            */
     
     
            Random rand = new Random();
            index = rand.nextInt(list.size());                              // sets index to a random location in the list ArrayList
     
        }
    }
     
    class sheepCreate{
        int xValue;
        int yValue;
     
    }

    as you can probably see, I did not have any luck. So my question now is, "is it possible to create objects using a loop", if not, I think I will just decide on a total number of sheep available and hard code each one in just like in the first example above.

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: General question on using array inside a nested for loop

    Why is the new class called sheepCreate? Class names should be nouns with an uppercase first letter. For example: Sheep
    The instances of the Sheep class should be saved in a collection like an ArrayList.
    For example
    Create an ArrayList to hold Sheep just like you did for Integer
    begin loop for number of sheep
    get the x and y values for the next location
    create an instance of Sheep
    save the x and y values in that instance
    save/add that instance to the list
    end loop
    After the loop the list has Sheep objects that contain their x,y locations.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Switch case with nested if inside
    By deadlynerd in forum What's Wrong With My Code?
    Replies: 4
    Last Post: July 16th, 2014, 04:01 AM
  2. nested array loop
    By jbenz in forum What's Wrong With My Code?
    Replies: 7
    Last Post: November 7th, 2013, 10:14 PM
  3. Jagged array loop question
    By Dankaru in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 14th, 2012, 09:21 AM
  4. Adding array elements inside a loop
    By Scotty in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 28th, 2010, 09:48 PM
  5. do while loop with nested while question
    By johneusmc in forum What's Wrong With My Code?
    Replies: 10
    Last Post: October 6th, 2010, 04:45 PM