1

So this is what I have so far.

public static int[][] generateRandomPositions(int number, int width, int height){

    for(int j=0; j <number; j++){
         int[][] pos = new int[][]{
             {Utility.randomInt(width),Utility.randomInt(height)}

         };

    }

    return [][]pos;
}

Basically the method gets a number which is the number of rows there should be and the width and height is the two numbers that will be in the two columns. Those of which are randomly generated between the number given (ex Utility.randomInt(5) would be between 0 and 5). The problem I am having is figuring out how to create the number of rows based off the number that is inputted. What I have I don't believe works. This is an example of what the out come should be if these numbers were inputted.

generateRandomPositions(4, 5, 30)
int[][] posB = new int[][] {
{ 3,21 }, 
{ 4,15 },
{ 1,17 }
{ 3,9 }
};

There are 4 rows because 4 was inputted as the number. The other numbers were randomly generated. So I just need help figuring out how to create the number of rows based off the numbers variable inputted. I am fairly new to programming so and suggestions and help would be greatly appreciated.

John Smith
  • 37
  • 1
  • 8
  • You need read up on how to create arrays in Java: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html – markspace Sep 10 '17 at 23:43
  • I understand how to create arrays I just don't know how to create one when there is a different possible amount of rows based on what is put into the method. – John Smith Sep 10 '17 at 23:51
  • Seriously? Does Google not work for you? Here's the first hit I get: https://stackoverflow.com/questions/12231453/syntax-for-creating-a-two-dimensional-array Just replace the number with a variable name. – markspace Sep 10 '17 at 23:52
  • Here's a more direct answer. Again, Google is your friend: https://stackoverflow.com/questions/27939594/initialize-two-dimensional-string-array-with-dynamic-size-in-java – markspace Sep 10 '17 at 23:57
  • Possible duplicate of [initialize two dimensional string array with dynamic size in java](https://stackoverflow.com/questions/27939594/initialize-two-dimensional-string-array-with-dynamic-size-in-java) – markspace Sep 10 '17 at 23:58
  • Right so I would do int[][] posB = new int[number][2] but then how would I get those random numbers in? – John Smith Sep 11 '17 at 00:01

1 Answers1

0
public static int[][] generateRandomPositions(int number, int width, int height){
    int[][] pos = new int[number][2];
    for(int j=0; j <number; j++){
       pos[j][0] = Utility.randomInt(width);
       pos[j][1] = Utility.randomInt(height);
    }
    return pos;
}
Kevin Anderson
  • 4,568
  • 3
  • 13
  • 21