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)
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!
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.
Related
After some research, I found out how to find the index of an item within a 2D Array. However, I'm after just one value, the row number and also what if the item you are looking for appeared more than once?
How would you store the row number of all those times?
for(int j = 0; j < size; j++)
{
if (arr[i][j] == 88)
{
return i; // The value i wanna store
break;
}
}
If the number 88 appears more than once, how can I store all the different locations and later retrieve it?
You could store the values you want in a List.
List<Integer> rows = new ArrayList<>();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (arr[i][j] == 88) {
rows.Add(i); // The value i wanna store
break; // exit inner loop and continue with next row
}
}
}
i'm after just one value, the row number
But if 88 appears more than once, how can I store all the different
locations and later retrieve it?
Considering you don't know how many duplicated copies of the value you're looking for there could be, I'd suggest using an ArrayList to store the indexes.
create this before the loops:
List<Integer> indexList = new ArrayList<>();
then within the if block simply add the index value for the value you've found to the ArrayList:
if (arr[i][j] == 88){
indexList.add(i);
break;
}
you can then return the ArrayList if your method requires returning the data:
return indexList; // after the loops have finished processing
However, if the method return type is void then you can simply ignore the return indexList;
How can I generate a 3 by 3 box layout in Java? I can do it hardcode, but I dont know how I will implement it when I use an ArrayList. I also don't know how I will create a 2d array with the use of an Arraylist. This is how I want my code to start:
for (int i = 0; i<ArrayList.size(); i++){
some content
}
Any ideas on how to start
It is possible, with an ArrayList<ArrayList<Integer>>, or any other type than Integer.
Essentially when you look at a multi-dimensional array you have an array of arrays of a certain type. In this case, to populate the array or print 3x3 ArrayList, you would iterate through them like you would with an array:
Given an ArrayList as such: ArrayList<ArrayList<Integer>> box
for (int i = 0; i < box.size(); i++) {
for (int j = 0; j < box.get(i).size(); j++) {
System.out.print(box.get(i).get(j));
}
System.out.println();
}
This is a very simple example. You can also use forEach loops as such:
for (ArrayList<Integer> row: box) {
for (Integer cell: row) {
System.out.print(cell);
}
System.out.println();
}
Note that initializing the list is a bit trickier with multiple "dimensions":
for (int i = 0; i < 3; i++) {
box.add(new ArrayList<Integer>());
for (int j = 0; j < 3; j++) {
box.get(i).add(...);
}
}
Keep in mind that this answer uses very simple Java, there is definitely more graceful ways to do it. However, I suspect that this is probably for a homework, hence the type of answer given.
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.charAt(0) != '#') {
c++;
//looking to get dimensions of line segments from file.
dimensions = new int[c][4];
//Split my file input into an array of tokens(strings)
tokens = line.split(",");
for (int i = 0; i < tokens.length; i++) {
//Parse strings to int.
dimtoke[i] = Integer.parseInt(tokens[i]);
for (int k = 0; k < dimensions.length; k++) {
for (int j = 0; j < dimensions[0].length; j++) {
//attempt to fill 2d array with contents from file.
dimensions[k][j] = dimtoke[j];
}
}
}
}
}
I get a 2d array full of the last dimension in the file instead of all the dimensions. The dimensions come in groups of 4 in a single line of text, so i made a single array with those tokens from each line i read in from the file so i could parse them to ints. something is happening in the process of transferring the 1d array of ints to the 2d array.
You have to close {} the tokens loop like this:
for (int i = 0; i < tokens.length; i++) {
//Parse strings to int.
dimtoke[i] = Integer.parseInt(tokens[i]);
}//you need a closing here
for (int k = 0; k < dimensions.length; k++) {
for (int j = 0; j < dimensions[0].length; j++) {
//attempt to fill 2d array with contents from file.
dimensions[k][j] = dimtoke[j];
}
}
I'll try to explain it to you.
Everytime you get an int in tokens with the instruction
dimtoke[i] = Integer.parseInt(tokens[i]);
Before getting the next int in dimtoke[i+1] you get into a loop where you fill all the ints in the 2d array with that dimitoke[i].
When those loops have finished(all the 2d array has been filled with only 1 int), you go again up and fill the dimitoke with the next int, and again, fill all the 2d array with that int.
What you need to do is to first finish the for loop and fill the dimitoke with the whole set of ints, and then, fill the 2D array with the ints in dimitoke.
Your problem was that you filled the whole array everytime you put an int in dimitoke, so everytime the whole 2d array was overwritten with only 1 int.
Another thing I expect to be wrong:
When you are filling the 2D array, you put the j variable in both dimensions and dimitoke, so if dimitoke lenght is not equal than the second array lenght of dimensions, you'll fill again every row with the same if dimitoke is greater, and indexOutOfBounds Excepcion if it's lesser. Here's an example:
dimitoke dimension = 10 = {0,1,2,3,4,5,6,7,8,9}
if dimensions have dimension 4, the output of dimensions will be:
0,1,2,3
0,1,2,3
0,1,2,3
.
.. c rows.
To repair that, what you can do is to change the dimitoke variable for a int n (for example) and change the code like this:
int n =0;
for (int k = 0; k < dimensions.length; k++) {
for (int j = 0; j < dimensions[0].length; j++) {
//attempt to fill 2d array with contents from file.
dimensions[k][j] = dimtoke[n];
n++;
}
}
I hope the error is out now
Not completely know what you want to do. But I think you should separate the two loop:
assign value to the dimtoke.
assign value to dimensions.
So I think apparently, you should enclose the loop here:
for (int i = 0; i < tokens.length; i++) {
//Parse strings to int.
dimtoke[i] = Integer.parseInt(tokens[i]);
}
I am trying to replace rows from an original 2d array to a updated 2d array. Problem is it won't store the last element during the replacement.
Here's my code:
String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}};
String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}};
for (int i = 0; i < updatedArray.length;i++ ) {
for (int j = 0; j < updatedArray[i].length; j++){
for(int x = 0; x < originalArray.length;x++){
for(int z = 0; z < originalArray[x].length;z++){
if(originalArray[x][0].equals(updatedArray[i][0])) {
updatedArray[i][j] = originalArray[x][j];
System.out.println("There's a match!!");
}else{
System.out.println("No match!");
}
}
}
}
}
System.out.println("originalArray:");
System.out.println(Arrays.deepToString(originalArray));
System.out.println("updatedArray:");
System.out.println(Arrays.deepToString(updatedArray));
For example, initially updatedArray in last row "purple" has {"purple","a","b","c"}. When it does the replacement using values from originalArray, the code above only outputs:
... [purple, nn, mm, bb]
which is wrong because it doesn't add the last element "hello". It should output:
... [purple, nn, mm, bb, hello]
I am aware the problem is in this line:
updatedArray[i][j] = originalArray[x][j];
Problem is no matter what I try to change originalArray[x][j] to originalArray[x][z] ... its screws up everything.
Any ideas on this? Still trying to get the jist of 2D arrays.
If there is a match, instead of trying to set each element in the updatedArray to the corresponding element in the original array you can just set the entire array to the original array.
String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}};
String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}};
for (int i = 0; i < updatedArray.length;i++ ) {
for (int j = 0; j < originalArray.length; j++){
if(originalArray[j][0].equals(updatedArray[i][0])) {
updatedArray[i] = originalArray[j];
System.out.println("There's a match!!");
}else{
System.out.println("No match!");
}
}
}
The issue is how you chose to iterate over the dimensions of updatedArray which are different than the dimensions of originalArray.
Let just look at the case i=2 which is the 'row' for purple:
for (int j = 0; j < updatedArray[i].length; j++){
updatedArray[i=2].length = 4
in updated:
index = 0 , 1 , 2 , 3
{"purple","a","b","c"}
in original:
index = 0 , 1 , 2 , 3 , 4
{"purple","nn","mm","bb","hello"}
Therefore since j will always be < 4 it can never be used to index originalArray[x][4] = "hello"
DANGER: this code also doesn't handle the fact that you would need to extend the purple array for updatedArray. Java may do some magic to handle this for you but I wouldn't trust it to work that way.
Suggestion:
- compare the lengths of each row and allocate extra memory where necessary before copying data from originalArray to updatedArray
- if possible just copy the whole row between original and updated.
So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.