Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding more than 1 thing into a Java Array

For this program, I am supposed to add two different kinds of ‘mirrors’ (the forward and backward slashes represent mirrors in my game) which is ‘/’ and ‘\’. I have successfully added the first set of slashes into my maze array but I can’t seem to figure out how to add both of the different slashes at the same time.

public static void placeMirrors(){
    Scanner input = new Scanner(System.in);

    // Promopting user for how many mirrors they want
    System.out.print("\nHow many mirrors do you want in your maze?");
    System.out.print("The maximum number of mirrors you can have is 8. The minimum is 2.\n");
    int usersMirrors = input.nextInt();

    // Deploying mirrors randomly within the maze
    for (int i = 1; i <= usersMirrors;) {
        int x = (int)(Math.random() * numRows);
        int y = (int)(Math.random() * numCols);

        // *FIGURE OUT ADDING BOTH SETS AT ONCE THING*
        if((x >= 0 && x < numRows) && (y >= 0 && y < numCols) && (maze[x][y] == ".")) {
            maze[x][y] = "\\";
            i++;
        }
    }
    System.out.println("Mirrors placed.");
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think you just need to add a second if inside the loop. I assume you’re adding the "mirrors" in pairs.

// Deploying mirrors randomly within the maze
for (int i = 1; i <= usersMirrors;) {
    int x = (int)(Math.random() * numRows);
    int y = (int)(Math.random() * numCols);

    if((x >= 0 && x < numRows) && (y >= 0 && y < numCols) && (maze[x][y].equals( "." ) )) {
        maze[x][y] = "\\";
        i++;
    }

    x = (int)(Math.random() * numRows);
    y = (int)(Math.random() * numCols);

    if((x >= 0 && x < numRows) && (y >= 0 && y < numCols) && (maze[x][y].equals( "." ) )) {
        maze[x][y] = "/";
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading