简体   繁体   中英

Why can I not store a value in my 2d String array from my normal String Array

I need to create a 2d with 2 rows, one to hold unique string and the other the number of times the string appeared in the string array im getting the words form, cannot put values into my 2d because its null.

public lexNode() throws IOException {

    path = "src\\words.txt";
    String content = Files.readString(Paths.get(path), StandardCharsets.UTF_8);
    allWords = content.split("[^a-zA-Z]+");
    String[][] allWords2 = new String[2][];
    String wordsUsed;

    for(int i = 0, j = 0; i < allWords.length; i++){
        wordsUsed = allWords[i];
        allWords2[1][j] = "1";

        if (!(wordsUsed.contains(allWords[i]))){
            allWords2[0][j] = allWords[i];
            allWords2[1][j] = "1";
            j++;
        }else if(wordsUsed.contains(allWords[i])){
           int idx = Arrays.asList(allWords2[0]).indexOf(allWords[i]);
            allWords2[1][idx] = Integer.toString(Integer.parseInt(allWords2[1][idx]) + 1);
        }
    }

I tried putting in values before the for loop, I cant use hashmaps because the getKey wont find the string I'm looking for, its always false as i altered the hashmap to count number of occurrences a word appeared. Thats a question for another thread.

See below how 2D arrays are defined & declared (or memory allocated) before values can be assigned.

 public class Main {
       public static void main(String[] args) {
          versionOne();
          versionTwo();
       }
       public static void versionOne() {
           String[][] allWords2 = new String[2][];   //2d is defined 
          allWords2[0] = new String[2]; // inner array allocated
          allWords2[0][0] = "Hello";
          allWords2[0][1] = "World";
           System.out.println("Ver1>> " + allWords2[0][0] + " " + allWords2[0][1]);
      }
      public static void versionTwo() {
           String[][] allWords2 = new String[2][2];   //2d is defined & allocated
   
          allWords2[0][0] = "Hello";
          allWords2[0][1] = "World";
           System.out.println("ver2>> " + allWords2[0][0] + " " + allWords2[0][1]);
      }
    }

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