Is there a way to print all values in a 3d array?
This is what I got but getting a null pointer exception:
int i = 2;
int x = 15;
String[][][] arrays = new String[x][x][i];
String arraytext = "hello";
for (String[][] row: arrays)
Arrays.fill(row, arraytext);
for (int a = 0; a<=x; a++){
for (int b = 0; b<=x; b++){
for (int j = 0; j<=i; j++)
{System.out.println(arrays[a][b][j]);}
}
}
You have a problem filling your array. you are getting
java.lang.ArrayStoreException: java.lang.String at Arrays.fill(row, arraytext);
That is cause you are trying to add a String when is expected an String[][].
And for printing you can use Arrays.deepToString() is your answer.
System.out.println(Arrays.deepToString(arrays));
Example:
public static void main(String[] args) {
String[][][] array3d = new String[10][10][10];
for(String [] [] array2d : array3d){
for(String[] array : array2d){
Arrays.fill(array, "hello");
}
}
System.out.println(Arrays.deepToString(array3d));
}
The problem is that this:
for (String[][] row: arrays)
Arrays.fill(row, arraytext);
Is trying to pass row, which is a double array of strings, to a function expecting a single array of strings. To get the bottom level of your 3D array, you want this:
for (String[][] slice: arrays)
for (String[] row: slice)
Arrays.fill(row, arraytext);
You also have both issues addressed by other answers in your double loop: You'll get an index out of bounds unless you change the <=s to <, and sub isn't defined.
You're going out of bounds on your arrays, instead of <= try <.
for (int a = 0; a < x; a++){
for (int b = 0; b < x; sub++){
for (int j = 0; j < i; j++)
{System.out.println(arrays[a][b][j]);}
}
}
Also, what is sub? You're code snippet should show where you define this variable.
Looks like you are experiencing off by 1 error (use < instead of <=):
for (int a = 0; a<x; a++){
for (int b = 0; b<x; b++){
for (int j = 0; j<i; j++)
{System.out.println(arrays[a][b][j]);}
}
}
Since you declared arrays as
String[][][] arrays = new String[x][x][i];
the bounds are from 0 to x-1 for the first two indexes, and 0 to i-1 for the thrid index.
Also, you're incrementing unknown variable sub rather than b in your second loop
You just forgot to replace a temporary value from copy-pastaing
for (int a = 0; a<=x; a++){
for (int b = 0; b<=x; sub++){ // sub here <---
for (int j = 0; j<=i; j++) {
System.out.println(arrays[a][b][j]);
}
}
}
Also see #jh314 's answer, your doing the off by one error
package academy.learnprogramming;
import java.util.Arrays;
public class Print3DArray {
public static void main(String[] args) {
// declare & initialize an int 3D array firstInt3D
int[][][] firstInt3D = {
{{1,2}},
{{3,4}},
{{5,6,7,8},{9,10}},
{{11},{12,13,14}},
};
// print all values of firstInt3D page by page
int x = 0;
for (int[][] accessPage: firstInt3D){
System.out.println("page:" + x);
if (x < firstInt3D.length) x++;
for (int[] accessRow: accessPage){
System.out.println(Arrays.toString(accessRow));
}
System.out.println();
}
}
}
Related
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.
I have a 2D array acting as a grid.
int grid[][] = new int[5][5];
How do I search through the grid sequentially as in (0,0), (1,0), (2,0), (3,0), (4,0) then (0,1), (1,1), (2,1) ... without getting any array out of bounds exceptions.
I'm new to programming and I just can't get my head around how to do this.
You know your lengths, now use a for loop to circle through the array.
for (int i = 0;i<5;i++){
for (int j = 0;i<5;i++){
int myInt = grid[i][j];
//do something with my int
}
}
To get the lengths at runtime you could do
int lengthX = grid.length; //length of first array
int lengthY = 0;
if ( lengthX>0){ //this avoids an IndexOutOFBoundsException if you don't know if the array is already initialized yet.
lengthY = grid[0].length; //length of "nested" array
}
and then do the for loop with lengthX and lengthY.
You will need two nested loop in order to access the two dimensions of your array:
int grid[][] = new int[5][5];
for(int i = 0; i < 5; i++ ) {
for(int j = 0; j < 5; j++ ) {
int value = grid[i][j];
}
}
Use 2 forloops like the following example:
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
System.out.println(grid[i][j]);
}
}
Also i would suggest that when initializing an array to write it like this:
int[][] grid = new int[5][5]; // note the double brackets are after int and not grid
Try this:
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
System.out.println(grid[j][i]);
}
}
This code (like the other answers) uses two for loops.
It does however add some handling of edge-cases
static int[] find(int[][] mtx, int valueToLookFor)
{
int rows = mtx.length;
if(rows == 0)
return new int[]{-1,-1};
int cols = mtx[0].length;
if(cols == 0)
return new int[]{-1, -1};
for(int r=0;r<rows;r++)
{
for(int c=0;c<cols;c++)
{
if(mtx[r][c] == valueToLookFor)
return new int[]{r,c};
}
}
return new int[]{-1,-1};
}
The question is:
Create a method display2DArray().
a) Inside the method, declare a 2D array that will hold the following integers:
{10,20} {11,21}
{15,25} {17,28}.
b) Display this information using two for loops.
public static void display2DArray()
{
int[][] arrays = new int[][]
{
{10, 20}, {11,21}, {15,25}, {17,28}
};
for(int i = 0; i < 3; i++)
{
for(int j = 0; i < 1; j++)
{
System.out.println(arrays[i][j]);
}
}
}
This is what ive come up with, but its not correct.
Can someone tell me what i need to be doing?
You are almost there!
Few things:
1) Typo - In your inner for loop, you are using an "j" instead of "i".
2) The same "j" must be j<=1 OR j<2 because you have 2 columns i.e. 2 elements in each sub-array. So the indexes will be 0 and 1.
3) In your outer for loop, you are using i<3. Since you have 4 rows i.e. 4 sub arrays, your indexes will be 0,1,2,3. So you need to use i<=3 OR i<4.
4) You can print an empty line in the outer for-loop for a better display.
for(int i = 0; i <= 3; i++) // Since you have 4 rows, indexes would be 0,1,2,3
{
for(int j = 0; j <= 1; j++) // Since you have 2 columns, indexes would be 0,1
{
System.out.print(arrays[i][j]+","); // Print each row i.e. sub-array
}
System.out.println(""); // Print an empty line after each row
}
This gives you the output:
10,20,
11,21,
15,25,
17,28,
In your second for loop, you have "i < 1" instead of "j < 1"
Use j in second array
public static void display2DArray()
{
int[][] arrays = new int[][]
{
{10, 20}, {11,21}, {15,25}, {17,28}
};
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 2; j++)
{
System.out.println(arrays[i][j]);
}
}
}
Also the boundaries were wrong
Your Problem with the inner loop the you used . You used i instead of J. So, Your loop will not give you the result as you Expected.
for(int i = 0; i < 3; i++)
{
for(int j = 0; j <= 1; j++) //use j instead of i here.
{
System.out.println(arrays[i][j]);
}
}
Thanks
for(int i = 0; i <= 3; i++)
{
for(int j = 0; j <= 1; j++)
{
System.out.println(arrays[i][j]);
}
}
1.) second for loop condition check is j< 1 not i< 1
2.) first for loop condition check is i<=3
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.
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];
}
}