error: cannot find symbol array.add(element);

后端 未结 5 1421
小蘑菇
小蘑菇 2021-01-29 11:34

I have a program that reads from a file, takes each word and adds it to an array as a String. I\'m having a bit of trouble with adding the Strings to the array. I get the e

5条回答
  •  梦毁少年i
    2021-01-29 11:54

    Use an ArrayList instead of an array:

    List array = new ArrayList();
    
    while (scanFile.hasNextLine()) {
        String line = scanFile.nextLine();
        Scanner lineInput = new Scanner(line).useDelimiter("\\s*");
        element = lineInput.next();
    
        // the add() method is available for Collections but
        // not for primitive arrays
        array.add(element);
        count++; 
     }
    
    for (String element : array) {
        System.out.print("Index = " );
        System.out.printf("%-7d", i);
        System.out.print(",  Element = ");
        System.out.println(element);
    }
    

提交回复
热议问题