简体   繁体   中英

Trying to determine if a string contains only letters in Java

My code is below:

} else if (words.toUpperCase().equals(words)) {
    for (int i = 0; words.length() > i; i++){
      thisLetter = words.charAt(i);
      letter = thisLetter.isLetter();
      if (!letter){
        break;
      }
    }  

letter is a boolean, thisLetter is a Character type (not a char). For some reason I get the following error when compiling:

 no suitable method found for isLetter()
method java.lang.Character.isLetter(int) is not applicable
  (actual and formal argument lists differ in length)
method java.lang.Character.isLetter(char) is not applicable
  (actual and formal argument lists differ in length)

Instead of letter = thisLetter.isLetter(); , which returns a primitive char . The returned value will be auto-boxed into a Character by the compiler

Character does not have a method isLetter() , instead, you should try...

letter = Character.isLetter(thisLetter);

Assuming of course, that thisLetter is a char ...

Consult the Java Docs for more details

Lessee:

boolean containsOnly = true;
for (int i = 0; i < words.length(); i++) {
    char theChar = words.charAt(i);
    int index = "Java".indexOf(theChar);
    if (index < 0) {
       containsOnly = false;
       break;
    }
}

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