简体   繁体   English

如何多次检查特定事件?

[英]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. 我的代码假定,如果*前后的字符相同,则用户将输入带有'*'(星号)的单词并显示“ same”。 For example, for the input ja'*'aisfun, my output should be "same" because a * is between to identical letters. 例如,对于输入ja'*'aisfun,我的输出应为“ same”,因为*介于相同字母之间。 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. 我的代码似乎适用于大多数情况,例如几颗星,但是当我尝试使用“ ja”, “ a”, “ isfun”之类的用户输入时,即使由于“ a”而应显示“ different”,输出仍是“ same”。和“ i”是不同的字母。 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 * . 它应该从1s.length() - 1 ,否则,如果最后一个或第一个字符是*则将导致索引超出范围异常。

Secondly, it seems like you want to output "DIFFERENT" if there is at least 1 pair of characters around a * that is different. 其次,如果*周围至少有一对字符不同,则似乎要输出“ DIFFERENT”。 You can do this by break ing out of the loop as soon as you find a pair that's different: 你可以做到这一点break ,你发现一对是荷兰国际集团不同圈外一旦:

// 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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM