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");
}
}
CodePudding user response:
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");
CodePudding user response:
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");
}
}
}