2D array populating not working - java

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.

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.

How do I convert a String into a 2D array

I have to define a method called getDistance. That takes the following string:
0,900,1500<>900,0,1250<>1500,1250,0 and returns a 2d array with the all the distances. The distances are separated by "<>" symbol and they are separated into each column by ",".
I know I need to use String.split method. I know splitting by the commmas will give me the columns and splitting it by the "<>" will give me the rows.
public static int[][] getDistance(String array) {
String[]row= array.split(",");
String[][] distance;
int[][] ctyCoord = new int[3][3];
for (int k = 0; k < row.length; k++) {
distance[k][]=row[k].split("<>");
ctyCoord[k][j] = Integer.parseInt(str[j]);
}
return ctyCoord;
This is a working dynamic solution:
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] _2d = null;
// let us take the column size now, because we already got the row size
if (rows.length > 0) {
String[] cols = rows[0].split(",");
_2d = new int[rows.length][cols.length];
}
for (int i = 0; i < rows.length; i++) {
String[] cols = rows[i].split(",");
for (int j = 0; j < cols.length; j++) {
_2d[i][j] = Integer.parseInt(cols[j]);
}
}
return _2d;
}
Let's test it:
public static void main(String[] args) {
String given = "0,900,1500<>900,0,1250<>1500,1250,0";
int[][] ok = getDistance(given);
for (int i = 0; i < ok.length; i++) {
for (int j = 0; j < ok[0].length; j++) {
int k = ok[i][j];
System.out.print(k + " ");
}
System.out.println();
}
}
I think you should first split along the rows and then the colums. I would also scale the outer array with the number of distances.
public static int[][] getDistance(String array) {
String[] rows = array.split("<>");
int[][] out = new int[rows.length][3];
for (int i = 0; i < rows.length, i++) {
String values = rows[i].split(",");
for (int j = 0; j < 3, j++) {
out[i][j] = Integer.valueOf(values[j]);
}
}
return out;

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

Java printing unicode characters in multidimensional arrays in columns + rows?

I have a small project to complete on my course but I'm a little stuck on solving this, basically I need to print the unicode characters in a multidimensional array to a table, 12 rows and 5 columns. So far I have this:
public class MultiArrTest {
public static void main(String[] args0) {
char[][] uc = new char[12][5];
int x = 64;
for (int i = 0; i < uc.length; i++) {
for (int j = 0; j < uc[i].length; j++) {
uc[i][j] = (char) x++;
System.out.print(uc[i][j] + " ");
System.out.println();
}
}
}
}
This prints the unicode but only in one column, I feel a bit silly here but could anyone give me a suggestion?
Thanks a lot.
Move the System.out.println(); outside the second for-loop and inside the first one, just after the for-loop:
for (int i = 0; i < uc.length; i++) {
for (int j = 0; j < uc[i].length; j++) {
uc[i][j] = (char) x++;
System.out.print(uc[i][j] + " ");
}
System.out.println();
}

Convert String into 2D int array

I have problem with conversion from String into two dimension int array.
Let's say I have:
String x = "1,2,3;4,5,6;7,8,9"
(In my program it will be String from text area.) and I want to create array n x n
int[3][3] y = {{1,2,3},{4,5,6},{7,8,9}}
(Necessary for next stages.) I try to split the string and create 1 dimensional array, but I don't have any good idea what to do next.
As you suggest I try split at first using ; then , but my solution isn’t great. It works only when there will be 3 x 3 table. How to create a loop making String arrays?
public int[][] RunMSTFromTextFile(JTextArea ta)
{
String p = ta.getText();
String[] tp = p.split(";");
String tpA[] = tp[0].split(",");
String tpB[] = tp[1].split(",");
String tpC[] = tp[2].split(",");
String tpD[][] = {tpA, tpB, tpC};
int matrix[][] = new int[tpD.length][tpD.length];
for(int i=0;i<tpD.length;i++)
{
for(int j=0;j<tpD.length;j++)
{
matrix[i][j] = Integer.parseInt(tpD[i][j]);
}
}
return matrix;
}
After using split, take a look at Integer.parseInt() to get the numbers out.
String lines[] = input.split(";");
int width = lines.length;
String cells[] = lines[0].split(",");
int height = cells.length;
int output[][] = new int[width][height];
for (int i=0; i<width; i++) {
String cells[] = lines[i].split(",");
for(int j=0; j<height; j++) {
output[i][j] = Integer.parseInt(cells[j]);
}
}
Then you need to decide what to do with NumberFormatExceptions
Split by ; to get rows.
Loop them, incrementing a counter (e.g. x)
Split by , to get values of each row.
Loop those values, incrementing a counter (e.g. y)
Parse each value (e.g. using one of the parseInt methods of Integer) and add it to the x,y of the array.
If you have already created an int[9] and want to split it into int[3][3]:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
toArray[i][j] = fromArray[(3*i) + j);
}
}
Now, if the 2-dimensional array is not rectangular, i.e. the size of inner array is not same for all outer arrays, then you need more work. You would do best to use a Scanner and switch between nextString and next. The biggest challenge will be that you will not know the number of elements (columns) in each row until you reach the row-terminating semi-colon
A solution using 2 splits:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
String[][] result = new String[x.length][];
for (int i = 0; i<x.length; i++) {
result[i] = x[i].split(",");
}
This give a 2 dimension array of strings you will need to parse those ints afterwards, it depends on the use you want for those numbers. The following solution shows how to parse them as you build the result:
String input = "1,2,3;4,5,6;7,8,9";
String[] x = input.split(";");
int[][] result = new int[x.length][];
for (int i = 0; i < x.length; i++) {
String[] row = x[i].split(",");
result[i] = new int[row.length];
for(int j=0; j < row.length; j++) {
result[i][j] = Integer.parseInt(row[j]);
}
}
Super simple method!!!
package ADVANCED;
import java.util.Arrays;
import java.util.Scanner;
public class p9 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
String x=sc.nextLine();
String[] array = x.split(",");
int length_x=array.length;
int[][] two=new int[length_x/2][2];
for (int i = 0; i <= length_x-1; i=i+2) {
two[i/2][0] = Integer.parseInt(array[i]);
}
for (int i = 1; i <= length_x-1; i=i+2) {
two[i/2][1] = Integer.parseInt(array[i]);
}
}
}

Categories

Resources