简体   繁体   中英

How to make 2D arrays and print them

Okay, so this program... I have no idea how to make it, let alone make it work. The goal of this program is to accept user INT values to be put into a 2d array (5 rows, 4 columns), output the array, and give the average value of each row. Any help on making it work and shortening it would be greatly appreciated.

import java.io.*;
class largeArray
{
    public static void main(String[] args) throws IOException
    {
    InputStreamReader inStream = new InputStreamReader (System.in);
    BufferedReader userInput = new BufferedReader (inStream);

    System.out.println("Welcome to the array making program.");
    System.out.println("Please enter the first 4 numbers:");

    int[][] datArray = new int[5][4];
    datArray[0][0] = Integer.parseInt(userInput.readLine());
    datArray[0][1] = Integer.parseInt(userInput.readLine());
    datArray[0][2] = Integer.parseInt(userInput.readLine());
    datArray[0][3] = Integer.parseInt(userInput.readLine());


    System.out.println("Please enter in the next 4 numbers:");
    datArray[1][0] = Integer.parseInt(userInput.readLine());
    datArray[1][1] = Integer.parseInt(userInput.readLine());
    datArray[1][2] = Integer.parseInt(userInput.readLine());
    datArray[1][3] = Integer.parseInt(userInput.readLine());


    System.out.println("Please enter in the third set of 4 numbers:");
    datArray[2][0] = Integer.parseInt(userInput.readLine());
    datArray[2][1] = Integer.parseInt(userInput.readLine());
    datArray[2][2] = Integer.parseInt(userInput.readLine());
    datArray[2][3] = Integer.parseInt(userInput.readLine());


    System.out.println("Please enter in the fourth set of numbers:");
    datArray[3][0] = Integer.parseInt(userInput.readLine());
    datArray[3][1] = Integer.parseInt(userInput.readLine());
    datArray[3][2] = Integer.parseInt(userInput.readLine());
    datArray[3][3] = Integer.parseInt(userInput.readLine());


    System.out.println("Please enter in the last set of numbers:");
    datArray[4][0] = Integer.parseInt(userInput.readLine());
    datArray[4][1] = Integer.parseInt(userInput.readLine());
    datArray[4][2] = Integer.parseInt(userInput.readLine());
    datArray[4][3] = Integer.parseInt(userInput.readLine());


    for(int row = 0; row < datArray.length; row++)
        { System.out.print("Row " + row + ": ");
        for (int column = 0; column < datArray[row].length; column++)
            System.out.print(datArray[row][column] + " ");
        System.out.println( );
        }
    }
}

Current issue: How do I get all values in the row to average out in a short hand way? IT also needs to output the average.

If you want the arrays to hold 5 objects, use:

int[][] datArray = new int[5][5];

Your error is that you set the length to:

int[][] datArray = new int[5][4];

So all internal arrays are of length 4 (index 0-3) and you cannot set value at index 4 in:

datArray[0][4] = Integer.parseInt(userInput.readLine());

BTW, I suggest you use loops here...

If you define int[][] datArray = new int[5][4]; you can't use the position datArray[x][4], it is out of bounds. You are asking for 25 number instead of the 20 you want, each row of numbers have the position 0,1,2,3,4 and it should be 0,1,2,3.

To calculate the avg of each row you can:

float[] avg = new float[5];

for(int i=0 ; i < 5 ; i++)
{
    float sum = 0;
    for(int j=0 ; j < 4 ; j++)
    {
        sum  += datArray[i][j];
    }
    avg[i] = sum/4;
}

You can add this info to the output message this way:

for(int row = 0; row < datArray.length; row++)
{
    System.out.print("Row " + row + ": ");
    for (int column = 0; column < datArray[row].length; column++)
        System.out.print(datArray[row][column] + " ");
    System.out.print("Row Average value: " + avg[row]);
    System.out.println( );
}

A shorter version:

import java.io.*;

class LargeArray {
    /**
     * Arrays dimension.
     */
    private static final int ARRAY_DIM_X = 4;
    private static final int ARRAY_DIM_Y = 5;

    public static void main(String[] args) throws IOException {
        BufferedReader tempReader = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Welcome to the array making program.");

        int[][] tempDatArray = new int[ARRAY_DIM_Y][ARRAY_DIM_X];

        for (int x = 0; x < ARRAY_DIM_Y; x++) {
            System.out.println(String.format("Please enter %1$s numbers:", ARRAY_DIM_X));
            for (int y = 0; y < ARRAY_DIM_X; y++) {
                tempDatArray[x][y] = Integer.parseInt(tempReader.readLine());
            }
        }

        printArray(tempDatArray);
    }

    private static void printArray(int[][] anArray) {
        for (int row = 0; row < anArray.length; row++) {
            System.out.print("Row " + row + ": ");
            for (int column = 0; column < anArray[row].length; column++) {
                System.out.print(anArray[row][column] + " ");
            }
            // now calculate the avrg ...
            System.out.println(" = " + calculateAverage(anArray[row]));
        }
    }

    private static float calculateAverage(int[] anArray) {
        float tempSum = 0f;
        for (int i = 0; i < anArray.length; i++) {
            tempSum += anArray[i];
        }
        return tempSum / anArray.length;
    }

}

您已经声明了int [] [] datArray = new int [5] [4],这意味着一个具有5行4列的二维数组,并且您在datArray [0] [4]处插入了第一行和第5列因此,将此异常更改为int [] [] datArray = new int [5] [5],它将起作用

To make it clear:

int[][] datArray = new int[5][4];

It goes from dataArray[0][0] to dataArray[4][3];

[5][4] means that you take first 5 digit and first 4 digit, which in Java means it goes from 0 to 4 and 0 to 3. In Java first number starts from 0, not 1.

Array starts from index 0 not 1 . In this code, int[][] datArray = new int[5][4]; you are bounding to 5 rows and 4 columns. but you are try for 5th column where the index is not available. So it throws ArrayIndexOutOfBoundsException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM