简体   繁体   中英

How to check if more than one character is uppercase in a string in Java

How to check if one string has more than one uppercase character (two or more next to each other) in Java? I've tried:

String word = scanner.nextLine();
for(int i=0;i<word.length();i++) {
char value = word.charAt(i);
if(Character.isUpperCase(value) && Character.isUpperCase(value+1) {
     System.Out.Print("There is more than one character uppercase");
   }
}

You are adding 1 to value , but value is a char .

I corrected this mistake, it should work now:

public boolean duplicateUpperCase(String word) {
    boolean lastUpperCase;
    for(int i = 0; i < word.length(); i++) {
        boolean upperCase = Character.isUpperCase(word.charAt(i));
        if (lastUpperCase && upperCase) return true;
        lastUpperCase = upperCase;
    }
    return false;
}

Now to check:

String word = scanner.nextLine();
if (duplicateUpperCase(word)) System.out.println("There is more than one character uppercase");

I think Character.isUpperCase(value+1) does not have the desired outcome in your case, it will simply add 1 to your character value, it will not get the next character in your word String . To get the next character try to use Character.isUpperCase(word.charAt(i+1)) .

Doing this, you should also be wary of StringIndexOutOfBounds exception, that's why word.length() > i+1 is being used:

 Scanner scanner = new Scanner(System.in);
 String word = scanner.nextLine();
 for(int i=0;i<word.length();i++) {
      if(Character.isUpperCase(word.charAt(i))) {
           if( word.length() > i+1 && Character.isUpperCase(word.charAt(i+1)) ){
               System.out.println("There is more than one character uppercase");
           }
       }
 }

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