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

2020-05-10 07:54发布

问题:

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

SortingWords.java:73: error: cannot find symbol
        array.add(element);
             ^

symbol: method add(String) location: variable array of type String[]

I have checked my spelling and all seems to be okay. What is happening and how can I fix it?

public class SortingWords {


 //global variables    
 public static int count = 0;

 public static void main(String [ ] commandlineArguments){
     String[ ] array = readFileReturnWords(commandlineArguments[0]);
     sortAndPrintArray(array, commandlineArguments[0]); 

     if (commandlineArguments.length != 1) {
        System.out.println("Please enter the INPUT file name as the   1st commandline argument.");
        System.out.println("Please enter exactly one (1) commandline arguments.");
        // Immediately terminates program
          System.exit(1);   
     }// end of if
     // if no commandline argument errors, continue program
       String inputFile = commandlineArguments[0];
 }

 /**
 * readFileReturnWords - Used To Read from File & Store Each Word in Array
 * 
 * @param inputFile is the name of the file  
 */

 public static String [] readFileReturnWords(String inputFile){
     //create array
     //read one word at a time from file and store in array
     //return the array
     //error checking for commandline input

     //make an array of Strings
     final Integer MAX = 100;
     String array[] = new String [MAX];
     String element = "";

     // read  items from file & store in array
     //connects to file 
      File file = new File(inputFile);
      Scanner scanFile = null;
      try {
        scanFile = new Scanner(file);
      } 
      catch (FileNotFoundException exception) {
        // Print error message.
       System.out.print("ERROR: File not found for " + inputFile);
      }

     // if made connection to file, read from file
     if (scanFile != null) {
       String firstLineOfFile = "";
       firstLineOfFile = scanFile.nextLine();

     // keeps looping if file has more lines..
       while (scanFile.hasNextLine()) {
          // get a line of text..
          String line = scanFile.nextLine();

          // divides each line by commas
          Scanner lineInput = new Scanner(line).useDelimiter("\\s*");
          element = lineInput.next();

          array.add(element);
          count ++; 
     }
   }
    System.out.println("Alphabetical (ASCII) listing of words in file: ");
    System.out.println("Index  Element");
    for(int i=0;i<MAX;i++){
       System.out.print("Index = " );
       System.out.printf("%-7d", i);
       System.out.print(",  Element = ");
       System.out.println(array[i]);
   }
   return array;
}

Much Thanks

回答1:

Really long boring answer, skip to bottom if you just want simple answer...

Ok buddy I think I see your issue here, I am going to start off by saying that you might be confusing STRING LISTS (be careful not to get confused lists can get very complicated and I am getting my masters in which there is an entire class on lists D= ) with STRING ARRAYS.

A list is a bag that you put various things in, like a grocery bag, you can put in carrots, peas, apples or in our case when programming in java strings, integerss ect... in a bag things do not have an order. An array is a more of like an oreo cookie container (array). You only put oreos in there and they all have go in a slot and stay there, which is unlike a grocery bag (list) where an item can fall to the bottom or the top....

This is important in an Array you cannot change the size so you cannot do

    array.add(element)

if you find yourself asking why then you need to think about it. What if you make an array that holds 2 elements? Then where does each element go? Even if you do not understand it, the Java language demands that in an Array you specify where objects go. So to add an object to an array you need to specify the location. Then set it equal to w/e you want for example,

The location,

    array[0];

Simple answer What you are setting it equal to,

    array[0] = "I want it to equal this string!!!";

End of Simple answer

Now lets look at the grocery bag (which does not have "slots" like an array) please note that it looks like there is no list in your code,

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

Once you have made this list THEN you can use the .add() that you used like so,

   myBrandNewShinyList.add("Let's add this string!!!");

Now you know the difference good luck. I made this same mistake so many times too...



回答2:

You are confused with array and ArrayList.

Arrays don't have add method, their insertion will be based on indexes

i.e

array[index] = value;

similary they can be retrived only with the index

i.e

value = arrray[index];


回答3:

Use an ArrayList instead of an array:

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

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


回答4:

Arrays in java have a static number of slots. You have to know the number you need at the time you instanciate the array.

What you want is either:

array[count] = element;

or you can use a List<String> (e.g. ArrayList<String>, since List is just an interface)



回答5:

That's not how you add an element to Java array. Keep a counter outside the loop that will be incremented inside the loop block and then add elements like below:

int i = 0;
while(.....){
    .
    .
    array[i] = //element to be added
    i++;
}