打印多维数组时出现问题

时间:2015-01-30 00:43:52

标签: java arrays printing multidimensional-array int

我创建了一个程序,要求用户输入行长度和列长度,然后创建一个“多维数组”。然后用零填充它。稍后,它将使用随机数填充每个组件,然后计算所有相邻单元格的总和,并将数字添加到相同大小的新数组中的当前位置。现在我只是用零打印出数组,但是当我这样做时,打印的阵列比我需要的更多。它似乎是打印出“排”次,但我不明白为什么。你们有什么帮助可以引诱我的方式吗?

import java.util.Scanner;

public class LAB1 {

public static void main(String args[]){

    Scanner keyboard = new Scanner(System.in);

    int row, column;


    //Ask user for row size
            System.out.print("Enter an integer from 5 to 20 for row size: ");
    //Make sure input is an int
            while(!keyboard.hasNextInt()){
                System.out.println("Not an integer. Try again: ");
                keyboard.next();
                }
    //Checks if input is out of bounds  
            row = keyboard.nextInt();
            while(row<5 || row>20){
                System.out.println("Not a valid row size. Please try again: ");
                row=keyboard.nextInt();}
    //Tells user row size
            System.out.println("Row size: "+row);       
    //Ask user for column size
            System.out.print("Enter an integer from 5 to 20 for row size.\nIt must be different from row size: ");
            column = keyboard.nextInt();
    //Checks if input is out of bounds or repeated 
            while(column==row || column<5 || column>20){
                    System.out.println("Not a valid column size. Please try again: ");
                    column=keyboard.nextInt();}
    //Tells user column size
            System.out.println("Column size: "+column);

            ProcessArray.ProcessArray(row, column);

                    }   
}


import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class ProcessArray{

private static int firstArray[][];
//private int secondArray[][];

static int[][] ProcessArray(int row, int column){
    firstArray = new int[row][column];
    ProcessArray.initializeArray(firstArray);
    return firstArray;
}

//fill first array with zeros
    public static void initializeArray(int[][] firstArray){
        for(int[] row: firstArray){
            Arrays.fill(row, 0);
            System.out.print(Arrays.deepToString(firstArray));

        }
    }
}

1 个答案:

答案 0 :(得分:1)

您正在为数组的每个元素打印出整个Array

for(int[] row: firstArray){
        Arrays.fill(row, 0);
        System.out.print(Arrays.toString(firstArray));

}

尝试

for(int[] row: firstArray){
        Arrays.fill(row, 0);
        System.out.print(Arrays.deepToString(row));

}

for(int[] row: firstArray){
        Arrays.fill(row, 0);
 }
 System.out.print(Arrays.deepToString(firstArray));