爪哇岛.为什么我的代码返回无限循环



它应该计算字符串中匹配对的数量。

public class tests {
    public static void main(String[] args) {
        System.out.print("Please enter a word: ");
        Scanner inpFirst = new Scanner(System.in);
        String inputF = inpFirst.nextLine();
        System.out.print("Please enter another word: ");
        Scanner inpSecond = new Scanner(System.in);
        String inputS = inpSecond.nextLine();
        int lenghtF = inputF.length() - 1;
        int lengthS = inputS.length() - 1;
        int f = 0;
        int s = 0;
        int matchingPairs = 0;
        while ((f < lenghtF) & (s < lengthS)) {
            char testF = inputF.charAt(f);
            char testS = inputS.charAt(s);
            if (testF == testS) {
                char testTwoF = inputF.charAt(f+1);
                char testTwoS = inputS.charAt(f+1);
                if (testTwoF == testTwoS)
                    matchingPairs = matchingPairs++;
            }
            System.out.println("jrfjtf");
            f = f++; 
            s = s++;
        }
        System.out.println("The number of matching pairs is: " + matchingPairs);

    }
}

将循环的最后两行更改为 f++s++

基本上,设置

f = f++

不递增值,它设置f=f,你只需要f++

正如 Masud 所提到的,将运算符从 && 和 &.大多数时候(尤其是使用 if 语句),您应该使用 && 运算符。

您使用了按位运算符&。使用 conditional and ( &&) 运算符,而不是在 while 循环中&

似乎您有增量问题。1.使用按位和运算符-"&"似乎没问题。它只是计算条件的两面并走很长的路,而不是像"if(foo != null && foo.doOpperation)那样做快捷方式,如果foo为null,右侧不会被检查,这样你可以避免'null引用错误'。2.您以错误的方式指控," f = f ++"将保持f原样。

Suggetions:在条件中使用 &&,使用 "f++;" 作为增量运算符。在这种情况下,另一个建议是使用 for 循环,您的条件很简单,对 f 和 s 的操作只是切口。

最新更新