Crazed
Crazed

Reputation: 117

Adding data into a 2-D array by columns

I am currently trying to construct a data table in Java for my data. However, my data is arranged in columns (so for one column header, say "amount run", I have an array for all the values of "amount run"). In other words, I have an array of values for all the values of "amount run", and I need to arrange those into a column and not a row. So my question is "is there a way to intialize a 2-D array so that one can initialize it column by column (since the only way I know of initializing a 2-D array is via doing

Object[][] array = { {"word1","word2"},{"word3","word4"}}

However, this is by rows and not by columns. So, how do I instead initialize it so that "word3" and "word2" are in the same "array" (as "word1" and "word2" are presently in the same "array").

(It's best if the solution does not use loops, but if that is the only way, that is fine)

Upvotes: 0

Views: 57

Answers (2)

user9209348
user9209348

Reputation:

To get the entire array filled in any way but the one you've already defined, you must know the length your array will be. You have two options when doing so. You may either preset a determined array length and width,

Object[][] array = new Object[3][27];

or you may ask the application user for one.

 System.out.print("Please enter an array length and column length: ");
 int m = input.nextInt();
 int x = input.nextInt();

 Object[][] array = new Object[m][x]; 

After you know your array size

    // If you are initializing by user input, then

    System.out.println("Enter column one: ");
    for (int i = 0; i < array.length; i++){
        for (int j = 0; j < array[i].length; j++){
            array[i][j] = input.nextLine();
        }
    }

    // Will not end until the column has finished by filled with the added user input.
    // You will loop until your entire array.length is filled



    // Same basic principle if you are not looking to use user input.

    for (int i = 0; i < array.length; i++){
         for (int j = 0; j < array[i].length; j++){
              array[i][j] = someObject;     // someObject meaning some predetermined value(s)
         }
    }

Hope this helps!

Upvotes: 1

J.del Rey
J.del Rey

Reputation: 101

Java dont have an especific constructor to do the task you are asking for, however you can resolve your problem with for loops.

for (int i = 0; i < columns; i++){
       for(int j = 0; j < rows ; j++){
               array[j][i] = “word” //initialize with some value
       }

}

With this code you are able to initialize the array column by column.

Upvotes: 0

Related Questions