简体   繁体   中英

How can I get the length of an element in a String array (getting errors)?

I know this question has been answered elsewhere, and I thought I knew the answer before (array[].length), but I'm getting the error message

Error: cannot find symbol
symbol: variable length
location: class java.lang.String

Here's the snippet of code:

    String[] langs = {"Arabic", "Spanish", "Chinese", "English", "Hindi", "Bengali"};
    for (int i = 0; i <= langs.length; i++){
        while (! search.equalsIgnoreCase(langs[i])){
            for(int j = 0; j <= langs[i].length; j++){
                //space for unfinished logic code; under construction
            }
        }
    }
}

As you can see, I have my string array, I'm creating a for loop that'll loop the number of times to the amount of available strings, and I'd previously created an input Scanner named "search", so while search doesn't equal any of the String arrays, it goes through another for loop that I intend to test each token in each string of the array against whatever the user typed in (I'm trying to create a suggestion if the user misspells a word where, if at least five of the tokens are the same throughout both strings [five letters are the same], it'll spit out the closest match to the user's String). I don't understand why I'm getting that error message, though. Any help would be appreciated.

To get the length of a String (as in your for-j loop), use .length(), as a method call; not .length as a property. Confusingly, in Java, arrays have .length, and strings have .length()

String reference

You need to use length() for the string and also:

langs.length equals 6 langs[6].length doesn't exist <= langs.length should probably be < langs.length;

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