将整数插入到2d数组中

时间:2015-11-27 10:53:15

标签: java

private void enterbtnActionPerformed(java.awt.event.ActionEvent evt) {                                         
        int [][] array = new int [4][4]; // my array

        for (int i = 0; i < array.length; i++)
        {
            for (int j = 0; j < array[i].length; j++)
                array[i][j]= ;// use for feeding the code 
        }
        popfield.setText(Arrays.deepToString( array ) );     
 }                         

我想通过2个文本字段将整数插入到2d数组中,一个用于列,一个用于行元素,通过两个文本字段xfield和yfield

2 个答案:

答案 0 :(得分:0)

我不认为你明白2D阵列是什么

把它想象成一个网格。您一次插入一个单元格。

单个单元属于一行和一列因此具有行号和列号...就像excel工作簿一样?细胞b5?

所以,如果你想输入数字,你只需要一个文本字段就可以调用它txt

其余如下

private void enterbtnActionPerformed(java.awt.event.ActionEvent evt)                                         
{

    int [][] array = new int [4][4]; // my array

    for (int i = 0; i < array.length; i++)

    {

        for (int j = 0; j < array[i].length; j++)

            array[i][j]= Integer.parseInt(txt.getText());// use for feeding the code 



    }

    popfield.setText(Arrays.deepToString( array ) );

}

答案 1 :(得分:0)

所以..对于创建2D int 数组:

    //int 2 dimensional array
    int[][] array = null;

    //your fields values
    final int xFieldVal = 5;
    final int yFieldVal = 7;

    //values to fill into array
    final int minArrayVal = 50;
    final int maxArrayVal = 100;

    //create matrix / grid with dimensions (xFieldVal x yFieldVal)
    array = new int[xFieldVal][yFieldVal];

(创建recangle xFieldVal x yFieldVal-或Y * X ..)

当您有矩形数组时,您可以访问以填充所有值,例如。那样:

    //random generator
    Random rnd = new Random();

    for (int i = 0; i < xFieldVal; i++) {
        for (int j = 0; j < yFieldVal; j++) {
            //generate new int in interval
            array[i][j] = minArrayVal + rnd.nextInt(maxArrayVal- minArrayVal+ 1);
        }
    }

虽然你没有矩形阵列(你可以有例如。第一维固定,第二维不是 - 我的意思是每个&#34;行&#34;可以有差异&#34;列&#34; count),你必须使用那个循环:

    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < array[i].length; j++) {
            System.out.print(array[i][j] + " ");
        }
        //printing next line
        System.out.println();
    }

EG。要找到最小值和最大值,您可以使用:

    //set on the max possible (every value should be less than that)
    int min=Integer.MAX_VALUE;
    //set on the min possible (every value should be more than that)
    int max=Integer.MIN_VALUE;
    //iteration through 1st index (eg. iteration through rows)
    for (int i = 0; i < array.length; i++) {
        //iteration through 2nd index of 1st index (eg. through all columns)
        for (int j = 0; j < array[i].length; j++) {
            //compare and assign if array value is less than actual found min
            if(min > array[i][j]){
                min = array[i][j];
            }
            //compare and assign if array value is more than actual found max
            if(max < array[i][j]){
                max = array[i][j];
            }
        }
    }