Matrix Filler Block

前端 未结 1 918
迷失自我
迷失自我 2021-01-24 12:10

In my class we have to make a matrix filler program but I have gotten very confused on how to do so by using the user input and I don\'t know how to at all. Iv\'e tried to start

相关标签:
1条回答
  • 2021-01-24 12:33

    By your example code it seems that what you are missing is basic syntax knowledge. Let me refresh your memory on arrays at the most basic level with simple language.

    Arrays are like a multi-dimensional list of variables of some type.

    • You choose the type of variables when you declare the array.
    • The amount of variables which an array can hold is a constant number (the length of the array) which is defined when is is initialized.
    • An array can also have more than one dimensions. You set the number of dimensions when you declare the array. Think of a 1 dimensional array as a list, 2 dimensions would turn the list into a matrix. In this case, you need to set the length of each dimension (when you initialize). So, if the length of the 2 dimensions is the same you get a square, otherwise you get a rectangle.

    Here is some code to go along with this:

    int[] myArray;
    

    Here I declared a 1 dimensional array which holds ints.

    myArray = new int[6];
    

    Here I initialized my array and set the length of the dimension to 6.

    int[] myArray2 = new int[7];
    

    I can also do them on the same line.

    long[][] myMatrix = new long[3][2];
    

    Here I declared a 2 dimensional array which holds longs. The lengths of the dimensions are 3 and 2, so it looks like this when you imagine it:

    _ _
    _ _
    _ _
    

    Now we wan to access the array at a certain position. This is done by specifying the array name and the position in each dimension you want to access, like this:

    myMatrix[0][1] = 63;
    

    Remember! The position start counting from 0, so a 2 by 3 array would have the first dimension values 0 and 1; and the second dimension values 0, 1 and 2.

    Now let's iterate over an array and put the number 6 in all of its slots:

    int[][] exmaple = new int[3][3]; // 2 dim. array of ints with size 3 by 3.
    for (int x = 0; x < 3; x++) {
        for (int y = 0; y < 3; y++) {
             example[x][y] = 6;
        }
    }
    

    Not sure if you need this, but I will mention a few additional notes:

    • You can initialize an array with values directly and then you don't need to specify the dimensions' lengths:

      int[][] array = new int[][] {{1 ,2}, {5, 65}}; // 2 by 2
      
    • You can get the length of a dimension of an array by the syntax

      array.length;    
      array[0].length;
      array[1].length;
      // etc.
      

      These return an int which you can use as a bound when looping:

      for (int i = 0; i < array.length; i++) {
         // ...
      }
      
    0 讨论(0)
提交回复
热议问题