Java: Storing values in 2D Array - java

I have a problem with storing values in a multidimensional array. The main concept of the idea is that I have an arraylist which is called user_decide and I transform it in a array. So, the decide array looks like [1, 45, 656, 8, 97, 897], but all the rows don't have the same number of elements. Then, I split this replace [,] and spaces and I would like to store each value individually in a 2D array. So, I split it with the "," and try to store each value in a different position. Everything seems to be printed great, even the cut[j] is what I want to store, but I get a java.lang.NullPointerException, which I don't get. The count variable is actually the count = user_decide.size()
String [] decide = user_decide.toArray(new String[user_decide.size()]);
for (int i = 0; i < count; i ++){
decide[i] =
decide[i].replaceAll("\\s", "").replaceAll("\\[","").replaceAll("\\]", "");
}
String [][] data1 = new String[count][];
for (int i = 0; i < count; i++){
String [] cut = decide[i].split("\\,");
for (int j = 0; j < cut.length; j++){
System.out.println(cut[j]);
data1[i][j] = cut[j];
}
}
Another question is why I cannot store it in a Int [][] array? Is there a way to do that?
Thank you a lot.
** EDIT **
I just made an edit about my answer after I accepted the question. I am trying to store it in a 2D int array.
String [][] data1 = new String[user_decide.size()][];
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
data1[i] = decide[i].split("\\,");
for (int j = 0; j < data1[i].length; j++) {
data[i] = new int [data1[i].length];
data[i][j] = Integer.parseInt(data1[i][j]);
System.out.println(data1[i][j]);
}
}

Ivaylo Strandjev's answer shows the reason for your problem. But there's a much simpler solution:
String [][] data1 = new String[count][];
for (int i = 0; i < count; i++){
data1[i] = decide[i].split("\\,");
System.out.println(Arrays.toString(data1[i]));
}
Also, you don't need to escape the comma.
EDIT
Saw your edit. There is a big mistake, see my comment in your code:
String [][] data1 = new String[user_decide.size()][];
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
data1[i] = decide[i].split("\\,");
for (int j = 0; j < data1[i].length; j++) {
data[i] = new int [data1[i].length]; // This line has to be prior to the
// inner loop, or else you'll overwrite everything but the last number.
data[i][j] = Integer.parseInt(data1[i][j]);
System.out.println(data1[i][j]);
}
}
If all you want is the int[], this is what I would do:
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
String[] temp = decide[i].split(",");
data[i] = new int [temp.length];
for (int j = 0; j < temp.length; j++){
data[i][j] = Integer.parseInt(temp[j]);
System.out.println(data1[i][j]);
}
}
There are probably nicer ways, but I don't know why you are using user_decide.size() ( a Collection) for the condition and decide[i] (an array) within the loop. There's no good reason I can think of mixing this, as it could lead to errors.

In java you will need to also allocate data[i], before copying contents:
for (int i = 0; i < count; i++){
data1[i] = new String[cut.length];
String [] cut = decide[i].split("\\,");
for (int j = 0; j < cut.length; j++){
System.out.println(cut[j]);
data1[i][j] = cut[j];
}
}
Before copying contents:

Related

when filling a 2d array it gets null values

Im trying to initialise all the elements of the 2d array into a string "EMPTY". but When ever I try to initialise the array it gets null values. I checked errors in the for loop but couldn't see any
public static void arr_2d(){
String [][] arr = new String[3][2];
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
}
for (int b = 0; b < arr.length; b++) {
for (int j = 0; j < arr[b].length; j++) {
System.out.print(arr[b][j] + " ");
}
System.out.println();
}
}
}
Your loops are nested wrongly, which will result in the filling process not being complete while you're trying to process its results. You need
public static void arr_2d() {
String[][] arr = new String[3][2];
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
}
}
for (int b = 0; b < arr.length; b++) {
for (int j = 0; j < arr[b].length; j++) {
System.out.print(arr[b][j] + " ");
}
System.out.println();
}
}
Actually for(int b) is in for(int i); that's why you observe null values. If you move for(int b) outside of for(int i), there will be no null values.
public static void arr_2d(){
String [][] arr = new String[3][2];
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
}
}
for (int b = 0; b < arr.length; b++) {
for (int j = 0; j < arr[b].length; j++) {
System.out.print(arr[b][j] + " ");
}
System.out.println();
}
}
Check the comments given below in the snippet:
public static void arr_2d(){
String [][] arr = new String[3][2];
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
// you can have the sysout statement here as well instead of having looping the entire array again.
System.out.print(arr[i][a] + " ");
}
// this loop must be executed separately inorder to check values present in the array or else you can have a sysout statement when assigning the "empty" value in the array.
for (int b = 0; b < arr.length; b++) {
for (int j = 0; j < arr[b].length; j++) {
System.out.print(arr[b][j] + " ");
}
System.out.println();
}
}
}
Although the answers you have are correct I will add that one problem is your code style is prone to errors.
Your mistake was traversing the array incorrectly. The correct way is traversing the array twice, one of filling and another for printing, but instead it seems you have attempted to do everything in one shot. That mistake can be avoided with a better code style.
This is how I would have written your code in imperative style:
String[][] arr = new String[3][2];
for (String[] a : arr)
Arrays.fill(a, "EMPTY");
for (String[] a : arr)
System.out.println(Arrays.toString(a));
Notice the code is much shorter, so there's less chances of mistakes. It's also a lot more obvious that you're traversing twice.
Instead of traversing an array explicitly:
for (int i = 0; i++; i < arr.length())
Use the implicit for loop:
for (String[] value: arr)
Instead of filling an array explicitly:
for (int a = 0; a < arr[i].length; a++) {
arr[i][a] = "EMPTY";
}
Use the already provided fill method:
Arrays.fill(value, "EMPTY");
Instead of printing an array explicitly:
for (String string : strings) {
System.out.print(string + " ");
}
System.out.println();
Use the already provided print method:
for (String[] a : arr)
System.out.println(Arrays.toString(a));
However, I would have written in functional style:
String [][] arr = new String[3][2];
Arrays.stream(arr)
.forEach(a -> Arrays.fill(a, "EMPTY"));
Arrays.stream(arr)
.map(Arrays::toString)
.forEach(System.out::println);
One particular advantage is that you are encouraged to think in a more abstract way. Instead of thinking how to explicitly set or print each element of the array, you are encouraged to use methods that implicitly traverse, transform or perform generic computations on all elements of the array.

2D array populating not working

I'm trying to populate a 2D array with char's from a string I've read in. I'm having a problem with actually populating this 2D array. It keeps printing a 2D array bigger than what I've given it, and the number always seems to be 6 rather than the letters from the string.
I store the string in an ArrayList called tempArray.
Input strings:
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
I instantiate a 2D array with columnlength = 11, and rowcount 3
epidemicArray = new int[rowCount][columnCount];
Array before I try to populate it:
00000000000
00000000000
00000000000
My code:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
for (int k = 0; k < rowCount; k++){
for (int l = 0; l < columnCount; l++){
epidemicArray[k][l] = charz[j];
}
}
}
}
}
Output: Which I didn't expect
6666666666666666666666
6666666666666666666666
6666666666666666666666
Expected output: (2D array)
WUBDLAIUWBD
LUBELUFBSLI
SLUEFLISUEB
Thanks, this is really bugging me.
Change your code to this:
public static void updateArray(){
//extract string from temp
for (int i = 0; i < tempArray.size(); i++){
String temp = tempArray.get(i);
char[] charz = temp.toCharArray();
for (int j = 0; j < charz.length; j++){
epidemicArray[i][j] = charz[j];
}
}
}
This edit should work since the number of columns is the length of one of the string (same length for the 3 of them).
Here is my output
[EDIT]. #magna_nz, I used the following methods to print the array
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
updateArray();
for (int i = 0; i < 3; i++) {
printRow(i);
}
}
This will print the numbers, but if you want to print characters you can change the above printRow method to something like:
public static void printRow(int rowNumber) {
for (int i = 0; i < 11; i++) {
System.out.print( (char)epidemicArray[rowNumber][i] + " ");
}
System.out.println();
}
And this will give you the following result:
You're overwriting your entire epidemicArray with the last value that charz[j] gets. Which is apparently 66. Actually you're overwriting that entire array with every value from charz and the last one won.

How to create multiple arrays with a loop?

I am having trouble creating multiple arrays with a loop in Java. What I am trying to do is create a set of arrays, so that each following array has 3 more numbers in it, and all numbers are consecutive. Just to clarify, what I need to get is a set of, let's say 30 arrays, so that it looks like this:
[1,2,3]
[4,5,6,7,8,9]
[10,11,12,13,14,15,16,17,18]
[19,20,21,22,23,24,25,26,27,28,29,30]
....
And so on. Any help much appreciated!
Do you need something like this?
int size = 3;
int values = 1;
for (int i = 0; i < size; i = i + 3) {
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = values;
values++;
}
size += 3;
int count = 0;
for (int j : arr) { // for display
++count;
System.out.print(j);
if (count != arr.length) {
System.out.print(" , ");
}
}
System.out.println();
if (i > 6) { // to put an end to endless creation of arrays
break;
}
}
To do this, you need to keep track of three things: (1) how many arrays you've already created (so you can stop at 30); (2) what length of array you're on (so you can create the next array with the right length); and (3) what integer-value you're up to (so you can populate the next array with the right values).
Here's one way:
private Set<int[]> createArrays() {
final Set<int[]> arrays = new HashSet<int[]>();
int arrayLength = 3;
int value = 1;
for (int arrayNum = 0; arrayNum < 30; ++arrayNum) {
final int[] array = new int[arrayLength];
for (int j = 0; j < array.length; ++j) {
array[j] = value;
++value;
}
arrays.add(array);
arrayLength += 3;
}
return arrays;
}
I don't think that you can "create" arrays in java, but you can create an array of arrays, so the output will look something like this:
[[1,2,3],[4,5,6,7,8,9],[10,11,12,13...]...]
you can do this very succinctly by using two for-loops
Quick Answer
==================
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
the first for-loop tells us, via the variable j, which array we are currently adding items to. The second for-loop tells us which item we are adding, and adds the correct item to that position.
All you have to remember is that j++ means j + 1.
Now, the super long-winded explanation:
I've used some simple (well, I say simple, but...) maths to generate the correct item each time:
[1,2,3]
here, j is 0, and we see that the first item is one. At the first item, i is also equal to 0, so we can say that, here, each item is equal to i + 1, or i++.
However, in the next array,
[4,5,6,7,8,9]
each item is not equal to i++, because i has been reset to 0. However, j=1, so we can use this to our advantage to generate the correct elements this time: each item is equal to (i++)+j*3.
Does this rule hold up?
Well, we can look at the next one, where j is 2:
[10,11,12,13,14...]
i = 0, j = 2 and 10 = (0+1)+2*3, so it still follows our rule.
That's how I was able to generate each element correctly.
tl;dr
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
It works.
You have to use a double for loop. First loop will iterate for your arrays, second for their contents.
Sor the first for has to iterate from 0 to 30. The second one is a little less easy to write. You have to remember where you last stop and how many items you had in the last one. At the end, it will look like that:
int base = 1;
int size = 3;
int arrays[][] = new int[30][];
for(int i = 0; i < 30; i++) {
arrays[i] = new int[size];
for(int j = 0; j < size; j++) {
arrays[i][j] = base;
base++;
}
size += 3;
}

String to int array [][] - JAVA

I have a board game define as
boardArray = new int[4][4];
and I have a string in this format:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]"
Is there a way to put it in the int array? Consider that it should look like this
[0,0,2,0]
[0,0,2,0]
[0,0,0,0]
[0,0,0,0]
You could simply do the following:
String s = "[[0,0,2,0],[0,0,2,0],[0,0,0,0],[0,0,0,0]]";
String myNums[] = s.split("[^0-9]+");
//Split at every non-digit
int my_array[][] = new int[4][4];
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++) {
my_array[i][j] = Integer.parseInt(myNums[i*4 + j + 1]);
//The 1 accounts for the extra "" at the beginning.
}
}
//Prints the result
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 4; j++)
System.out.print(my_array[i][j]);
System.out.println();
}
If you want to to it dynamically, I've written a librray: https://github.com/timaschew/MDAAJ
The nice thing is, that it's really fast, because internally it's a one dimensional array, but provides you same access and much more nice features, checkout the wiki and and tests
MDDA<Integer> array = new MDDA<Integer>(4,4);
or initialize with an existing array, which is one dimensional "template", but will be converted into your dimensions:
Integer[] template = new Integer[] {0,0,2,0, 0,0,2,0, 0,0,0,0, 0,0,0,0};
MDDA<Integer> array = new MDDA<Integer>(template, false, 4,4);
//instead of array[1][2];
array.get(1,2); // 2

size of Two-dimensional arrays in Java

I want to make a loop on Two-dimensional array in Java.
How I do that? I wrote:
for (int i = 0; i<=albums.size() - 1; i++){
for (int j = 0; j<=albums.size() - 1; j++){
But it didn't work. Thanks.
Arrays have a read-only field called length, not a method called size. A corrected loop looks like this:
for(int i = 0; i < albums.length; i++ ) {
for (int j = 0; j < albums[i].length; j++) {
element = albums[i][j];
You have to recognize that a 2-D array is just an array whose element type happens to be another array. So the i loop iterates over each element in albums (which is an array) and the j loop iterates over that child array (with a potentially different size).
A more transparent way would be like this:
String[][] albums;
for(int i = 0; i < albums.length; i++ ) {
String[] childArrayAtI = albums[i];
for (int j = 0; j < childArrayAtI.length; j++) {
String element = childArrayAtI[j];
}
}
Try this if you are working with Java 1.5+:
for(int [] album : albums) {
for(int albumNo : album) {
System.out.print(albumNo + ", ");
}
System.out.println();
}
First of all, a two-dimensional array looks like this in Java:
int[][] albums = new int[10][10];
Now, for iterating over it:
for (int i = 0; i < albums.length; i++) {
for (int j = 0; j < albums[i].length; j++) {
int value = albums[i][j];
}
}

Categories

Resources