【问题标题】:Problems printing a multidimensional array打印多维数组的问题
【发布时间】:2015-01-30 00:43:51
【问题描述】:

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

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));

        }
    }
}

【问题讨论】:

    标签: java arrays printing multidimensional-array int


    【解决方案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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多