Home > Back-end >  Modify this program find any 3 or more characters in sequence
Modify this program find any 3 or more characters in sequence

Time:09-18

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.

  1. For two codepoints c1, c2 being in sequence, c1 must be exactly 1 less than c2, that is c1 == c2 - 1.
  2. You must use index i within your loop: s1.charAt(i) returns the character that can be found at index i in s1.
  3. You must not iterate s1.length() times, because you'll have to test against s1.charAt(i 1) and s1.charAt(i 2). Alternatively, you must not start the iteration at 0, if you'd test against s1.charAt(i-1) and s1.charAt(i-2). Think about the boundaries of your loop, carefully.
  4. The current loop breaks after the first iteration but you may want to break 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.

  • Related