This code compares the first 3 characters in the given string. But I need to find at least 3 characters in the string that are in a sequence. Ex. ABC is a sequence. Abc is not. Abcd is. AbCdeF is not.
String s1= "abcd";
int sec = 0;
for(int i = 0; i < s1.length(); i ){
char ch = s1.charAt(i);
if(ch < s1.charAt(1) 1 &&
s1.charAt(1) 1 < s1.charAt(2) 1)
sec = 1;
break;
}
if (sec == 1)
System.out.println("please try again");
else if (sec == 0)
System.out.println("Valid");
CodePudding user response:
You're on the right track, but got a few things wrong.
- For two codepoints c1, c2 being in sequence, c1 must be exactly 1 less than c2, that is
c1 == c2 - 1
. - You must use index
i
within your loop:s1.charAt(i)
returns the character that can be found at indexi
ins1
. - You must not iterate
s1.length()
times, because you'll have to test againsts1.charAt(i 1)
ands1.charAt(i 2)
. Alternatively, you must not start the iteration at 0, if you'd test againsts1.charAt(i-1)
ands1.charAt(i-2)
. Think about the boundaries of your loop, carefully. - The current loop
break
s after the first iteration but you may want tobreak
when you've found a sequence.
Since this question is probably homework, I won't show the corrected code. It's a good idea to use pencil and paper to get more insight in both, algorithms and bugs.