简体   繁体   中英

How can I check a specific occurance more than once?

I am a beginner coder. My code supposes that the user will enter a word with '*'(stars) and display "same" if the chars before and after the * are the same. For example, for the input ja'*'aisfun, my output should be "same" because a * is between to identical letters. My code seems to work for most cases such as several stars, however when I try a user input like "ja' 'a' 'isfun", the output is "same" even though it should display "different" because of 'a' and 'i' being different letters. I suppose my code is capable of checking only the first star in this case. How can I fix this problem? (Consider the stars wihout the apostrophes)

    String ind = "DIFFERENT";
    for (int i = 0; i< s.length(); i++) {
        if ((s.charAt(i) == '*') && (s.charAt(i-1)) == s.charAt(i+1))
            ind = "SAME";
        }
        System.out.print(ind);
    }
    System.out.print("NO");

You must limit the loop from the 2nd char up until the 2nd from the end and break when a match is found (I suppose):

String ind = "DIFFERENT";
for (int i = 1; i < s.length() - 1; i++) {
    if ((s.charAt(i) == '*') && (s.charAt(i-1)) == s.charAt(i+1)) {
        ind = "SAME";
        break;
    }
}
System.out.print(ind);

Also drop:

System.out.print("NO");

First, you need to fix your loop index. It should go from 1 to s.length() - 1 , otherwise you would get a index out of bounds exception if the last or first char is a * .

Secondly, it seems like you want to output "DIFFERENT" if there is at least 1 pair of characters around a * that is different. You can do this by break ing out of the loop as soon as you find a pair that's different:

// be careful of bounds of the indexes    
for (int i = 1; i< s.length() - 1; i++) {
    if ((s.charAt(i) == '*')) {
            if ((s.charAt(i-1)) == s.charAt(i+1)) {
                ind = "SAME";
            } else {
                ind = "DIFFERENT";
                break;
            }
        }
    }
    System.out.print(ind);

Alternatively, you could use a regex solution:

if (Pattern.compile("(.)\\*(?!\\1)").matcher(s).find()) {
    System.out.println("DIFFERENT");
} else {
    System.out.println("SAME");
}

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