简体   繁体   中英

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

ArrayList到数组

[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:

在chars

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM