2013-03-04 34 views
1

這是我聽不太懂行使用||的Java調用方法

return (match(regex.substring(1), s)|| match(regex, s.substring(1))); 

我的理解是,它會調用後者,如果第一種方法是錯誤的。所以我寫了一個簡單的程序來測試。

public static void main(String[] args) 
{ 
    System.out.println(test(5)); 
} 

public static boolean test(int a) 
{ 
    System.out.println(a); 
    if (a>10) 
     return true; 
    if (a==4) 
     return false; 
    else 
     return (test(a-1) || (test(a+1))); 
} 

但它只是打印5 4 6 5 4 6 ...

+0

名單什麼:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html – sadaf2605 2013-03-04 00:37:22

回答

3

邏輯或爲真,如果左側或右側表達式爲真。如果左表達式爲真,計算機語言可以選擇不評估正確的表達式以節省時間。事實上,Java正是如此。

這意味着,

match(regex, s.substring(1)) 

會當且僅當

match(regex.substring(1), s) 

是假執行。

所以返回值是:

  • 真正如果match(regex.substring(1), s)返回true,
  • match(regex, s.substring(1)的返回值,否則
+0

你能坐看看我添加的簡單程序?我不確定哪裏出了問題。 – otchkcom 2013-03-04 00:43:16

+0

您的新程序最終應返回* true *。在第一次調用5時,它會遞歸地調用它自己,首先以5-1 = 4(返回false),然後從||的左側開始。是假的,5 + 1 = 6。它將繼續前進,直到右側操作數大於10,此時迭代將終止,返回true。這不是你所期望的嗎?這不是你得到的嗎? – 2013-03-04 01:08:08

+0

我得到了Stackoverflow錯誤。但是,如果我將第一個條件設置爲== 6,它將返回true – otchkcom 2013-03-04 01:23:54

0

它等同於:

if match(regex.substring(1), s) return true; 
if match(regex, s.substring(1)) return true; 
return false; 
0

你寫的程序調用一個5作爲參數測試。這打印出五個。這不會超過4箇中的10個,所以它會轉到其他部分。在其他情況下,您可以遞歸地調用它自己的方法,第一次使用4。所以4打印這將返回一個錯誤。然後它嘗試第二個是+ 1,所以它調用一個6的測試。這將在屏幕上打印6,落到else,然後遞歸地調用測試,用一個(現在是6)-1這樣與一個5.這個循環是無止境的。

你必須把第一個如果:如果 (一== 4)

此修復程序,但不是你想要得到什麼。

另外問題是你使用邏輯或完全錯誤。 OR是爲了查看這兩個答案中的一個是否爲真。如果要根據情況調用方法,則必須使用if或三元運算符。

public static void main(String[] args) 
{ 
    System.out.println(test(5)); 
} 

public static boolean test(int a) 
{ 
    System.out.println(a); 
    if (a>10) 
     return true; 
    if (a==4) 
     return false; 
    else 
     if(test(a-1)) { 
      return test(a-1); 
     } 
     else { 
      return (test(a+1)); 
     } 
} 

這應該給你想要的我猜的java運營商的