2013-10-22 49 views
2

它应该计算字符串中匹配对的数量。Java。为什么我的代码返回无限循环?

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); 


    } 
} 
+1

由于循环退出条件取决于'f'和's',所以它是合理的试着在每次迭代时打印“f”和“s”值,而不是“jrfjtf”,这样只会显示你处于无限循环。 (也许你确实尝试了这个,但是你没有在这个问题中提及它,如果你确实尝试过了,那么你应该提到问题是值没有增加,这会帮助你找到重复的@RohitJain链接到。) –

回答

4

更改最后两行的循环,以f++s++

基本上,设置

f = f++

不增加价值,它集f=f,你只想f++代替。

正如Masud提到的,从& &和&更改您的运营商。大多数情况下(特别是if语句),您应该使用&&运算符。

1

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

+0

在Java中,单个&符号仍然是一个布尔检查,但它不是短路。 '(f

+0

我不认为这会实际上一个区别。 '(f MrAzzaman

0

好像你有一个增量问题。 1.使用按位和运算符 - '&'似乎没问题。它只是计算条件的两个方面,而不是像“if(foo!= null & & foo.doOpperation)”那样做快捷方式,如果foo为null,右侧将不会被检查,这样你就可以避免“空refferance错误” 2.你在一个错误的方式incrimenting,“F = F +”将保持F,其是

Suggetions:。用& &在调理和“F +”;如incremention运营商 这种情况下的另一个建议是使用for循环,你的条件很简单,并且f和s上的操作只是inceementation。