2016-04-29 99 views
-2

當我運行一個簡單的程序時,它們兩個(&和& &)似乎可以互換使用。有人可以解釋我什麼時候應該使用每個案例嗎?JAVA:邏輯AND/OR和短路AND/OR有什麼區別?

public class Test1 { 

    public static void main(String [] args){ 

     int counter = 0; 

     int dice1; 
     int dice2; 


    for (int loop = 0; loop <= 1000; loop++) { 


    dice1= (int) (Math.random()*6)+1; 
    dice2= (int) (Math.random()*6)+1; 

     if (dice1 == 6 && dice2 == 6){ 
      counter ++; 
     } 

    } 

    System.out.println("Counter = " + counter); 

    } 
} 

這個節目也似乎當我使用&,而不是& &工作。那有什麼區別?

+4

我在代碼中看不到'||'或'|'的任何用法。你能分享你的實際代碼嗎? – Mureinik

+0

我的意思是&和&&,我的不好 – TheHoboMaster

+0

你知道其中一個短路。你明白這是什麼意思嗎?如果你的測試是'test!= null && test.equals(「foo」)'?測試一下。 –

回答

0

的主要區別是,&&||運營商做一些「懶惰計算」

在這行代碼:

method1() & method2(); 

兩種方法將被調用的返回值的獨立的method1。在這行代碼另一方面:

method1() && method2(); 

method2纔會被調用,如果method1回報true

使用||時,只有在第一個方法返回false時纔會調用第二種方法。


相關問題