Doesn't save the words in array

馋奶兔 提交于 2020-04-30 09:24:50

问题


i've got a propably simple question. I try to read the file and i want to add each single word to my array "phrase". The problem occures in for loop. I got the exception "index 0 out of bounds for length 0". Can you please help me with that?

    String [] tokens;
    String line;
    String hash = " ";
    int n = 0;
    String [] phrase = new String [n];

    public void loadFile()
    {
        try
        {
            @SuppressWarnings("resource")
            BufferedReader br = new BufferedReader(new FileReader("z3data1.txt"));

            while((line = br.readLine()) != null)
            {
                tokens = line.split("[ ]");
                n += tokens.length;
            }
            for(int j = 0; j<tokens.length; j++)
            {
                phrase[j] = tokens[j];
            }
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
   }

回答1:


A couple observations.

  • you are getting the error because your array is not large
    enough and the index j is exceeding its size.
  • you keep overwriting tokens in the while loop. The while loop needs to encompass the copying of the tokens to the phrase array.

So try the following:

      while((line = br.readLine()) != null) {
              tokens = line.split("[ ]");
              n += tokens.length; // don't really need this.
          //starting offset to write into phrase
          int len = phrase.length;
          phrase = Arrays.copyOf(phrase,phrase.length + tokens.length);

          for(int j = 0; j<tokens.length; j++) {
              phrase[j + len] = tokens[j];
          }
       }

This statement

phrase = Arrays.copyOf(phrase,phrase.length + tokens.length)

Copies the contents of phrase and increases the array size to handle the writing of tokens.

Another (and probably preferred) alternative is to use a List<String> which grows as you need it.

List<String> phrase = new ArrayList<>();

for(int j = 0; j<tokens.length; j++) {
       phrase.add(tokens[j]);
}
// or skip the loop and just do
Collections.addAll(phrase,tokens);

One observation. I don't know what you are splitting on but your split statement looks suspicious.




回答2:


The issue you faced is because of the following declaration:

int n = 0;
String [] phrase = new String [n];

This declaration is equivalent to String [] phrase = new String [0]. Since phrase [] is of size 0, you will get ArrayIndexOutOfBoundsException when you try to add any string to it. You can understand it further with the help of the following example:

class Main {
    public static void main(String[] args) {
        String[] array = new String[0];
        array[0] = "Hello World!";
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
    at Main.main(Main.java:4)

Since you do not know the total number of tokens in the file, you should use a List instead of an array. List works as a dynamic array (i.e. an array whose size is not fixed).

List<String> phrase = new ArrayList<String>();

public void loadFile() {
    try {
        @SuppressWarnings("resource")
        BufferedReader br = new BufferedReader(new FileReader("z3data1.txt"));

        while ((line = br.readLine()) != null) {
            tokens = line.split("[ ]");
            for (String token : tokens) {
                phrase.add(token);
            }
        }
        System.out.println(phrase);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}



回答3:


You're setting n to 0, so phrase is also of length 0 when you say String[] phrase = String[n]. Therefore, you can't add anything to it.

If you want something of variable length, you can use an ArrayList. In the code below, you can directly use Collections.addAll to split up the line and put everything into the phrase ArrayList.

    String line;
    //Note that you can get rid of tokens here, since it's being inlined below
    ArrayList<String> phrase = new ArrayList<>();

    public void loadFile()
    {
        try
        {
            @SuppressWarnings("resource")
            BufferedReader br = new BufferedReader(new FileReader("z3data1.txt"));

            while((line = br.readLine()) != null)
            {
                //No need for a for-loop below, you can do everything in one line
                Collections.addAll(phrase, line.split("[ ]"));
            }
        }
        catch(IOException ex)
        {
            ex.printStackTrace();
        }
   }


来源:https://stackoverflow.com/questions/61272277/doesnt-save-the-words-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!