when filling a 2d array it gets null values - java

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.

Related

How do I copy a two dimensional array with null at the end?

[[4390, Apple, $1.59],[4046, Avocado, $0.59],null, null]
I am trying to copy the above two dimensional array with for loop, but I got:
[[4390, Apple, $1.59],[4046, Avocado, $0.59],[null, null, null],[null, null, null]
What should I do to get null instead of [null, null, null] without importing Array?
Following is my code. Assume the array I want to copy is called "marketItems"
int nullIndex = marketItems.length;
for(int j = 0; j < marketItems.length; ++j) {
if(marketItems[j] == null) {
nullIndex = j;
break;
}
}
String[][]copy = new String[marketItems.length][3];
for(int i = 0; i < nullIndex; ++i ) {
for(int j = 0; j < marketItems[i].length; ++j) {
copy[i][j] = marketItems[i][j];
}
}
for(int i = nullIndex; i < marketItems.length; ++i) {
marketItems[i] = null;
}
Well for practical code, you should be importing and using Arrays (or something) rather than implementing this by hand. But assuming that this is a learning exercise ...
The problem is this line:
String[][]copy = new String[marketItems.length][3];
This is explicitly allocating a rectangular 2-D array. But your requirement is for a ragged array where some of the first level subarrays are actually null.
This is a simpler, cleaner way of doing it:
String[][] copy = new String[marketItems.length][];
That allocates just the top-level array, with the sub-array references default initialized to null. Then you allocate sub-arrays as required for the non-null sub-arrays in the original marketItems object ... and populate them.
for (int i = 0; i < marketItems.length; i++) {
if (marketItems[i] != null) {
copy[i] = new String[marketItems[i].length];
for (int j = 0; j < marketItems[i].length; j++) {
copy[i][j] = marketItems[i][j];
}
}
}
(That is about half the number of lines of code in the original version. And it will be more efficient, and easier to understand for someone who can read Java.)
public class Test {
public static void main(String[] args) {
String[][] marketItems = new String[][]{
{"4390", "Apple"," $1.59"},{"4046", "Avocado", "$0.59"},null,null
};
int nullIndex = marketItems.length;
for(int j = 0; j < marketItems.length; ++j) {
if(marketItems[j] == null) {
nullIndex = j;
break;
}
}
String[][]copy = new String[marketItems.length][3];
for(int i = 0; i < nullIndex; ++i ) {
for(int j = 0; j < marketItems[i].length; ++j) {
copy[i][j] = marketItems[i][j];
}
}
for(int i = nullIndex; i < marketItems.length; ++i) {
// marketItems[i] = null;
copy[i]=null;
}
System.out.println(Arrays.deepToString(copy));
}
}

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 do I remove duplicates from two arrays?

I need to have an algorithm that changes values in one array if it is in the second array. The result is that the first array should not have any values that are in the second array.
The arrays are of random length (on average ranging from 0 to 15 integers each), and the content of each array is a list of sorted numbers, ranging from 0 to 90.
public void clearDuplicates(int[] A, int[] B){
for(int i = 0; i < A.length; i++){
for(int j = 0; j < B.length; j++)
if(A[i] == B[j])
A[i]++;
}
}
My current code does not clear all of the duplicates. On top of that it might be possible it will creat an index out of bounds, or the content can get above 90.
Although your question is not very clear, this might do the job. Assumptions:
The number of integers in A and B is smaller than 90.
The array A is not sorted afterwards (use Arrays.sort() if you wish to
fix that).
The array A might contain duplicates within itself afterwards.
public void clearDuplicates(int[] A, int[] B) {
// Initialize a set of numbers which are not in B to all numbers 0--90
final Set<Integer> notInB = new HashSet<>();
for (int i = 0; i <= 90; i++) {
notInB.add(i);
}
// Create a set of numbers which are in B. Since lookups in hash set are
// O(1), this will be much more efficient than manually searching over B
// each time. At the same time, remove elements which are in B from the
// set of elements not in B.
final Set<Integer> bSet = new HashSet<>();
for (final int b : B) {
bSet.add(b);
notInB.remove(b);
}
// Search and remove duplicates
for (int i = 0; i < A.length; i++) {
if (bSet.contains(A[i])) {
// Try to replace the duplicate by a number not in B
if (!notInB.isEmpty()) {
A[i] = notInB.iterator().next();
// Remove the added value from notInB
notInB.remove(A[i]);
}
// If not possible, return - there is no way to remove the
// duplicates with the given constraints
else {
return;
}
}
}
}
You can do it just by using int[ ] although it's a bit cumbersome. The only constraint is that there may not be duplicates within B itself.
public void clearDuplicates(int[] A, int[] B) {
//Number of duplicates
int duplicate = 0;
//First you need to find the number of duplicates
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++)
if (A[i] == B[j])
duplicate++;
}
//New A without duplicates
int[] newA = new int[A.length-duplicate];
//For indexing elements in the new A
int notDuplicate = 0;
//For knowing if it is or isn't a duplicate
boolean check;
//Filling the new A (without duplicates)
for (int i = 0; i < A.length; i++) {
check = true;
for (int j = 0; j < B.length; j++) {
if (A[i] == B[j]) {
check = false;
notDuplicate--;//Adjusting the index
}
}
//Put this element in the new array
if(check)
newA[notDuplicate] = A[i];
notDuplicate++;//Adjusting the index
}
}
public class DuplicateRemove {
public static void main(String[] args) {
int[] A = { 1, 8, 3, 4, 5, 6 };
int[] B = { 1, 4 };
print(clear(A, B));
}
public static int[] clear(int[] A, int[] B) {
int a = 0;
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
if (A[i] == B[j]) {
a++;
for (int k = i; k < A.length - a; k++) {
A[k] = A[k + 1];
}
}
}
}
int[] C = new int[A.length - a];
for (int p = 0; p < C.length; p++)
C[p] = A[p];
return C;
}
public static void print(int[] A) {
for (int i = 0; i < A.length; i++)
System.out.println("Element: " + A[i]);
}
}
Here is an example.. I compiled and its working. For any question just let me know :)
maybe you should try the following code:
public void clear (int[] A, int[] B)
{
for (int i=0; i<A.length;i++)
{
for (int j=0; j<B.length; j++)
if(A[i]==B[j])
{
for (int k=i; k<A.length;k++)
A[k]=A[k+1];
j=B.length-1; //so that the cycle for will not be executed
}
}
}

Print all values in a 3d array

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();
}
}
}

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