2012-10-05 20 views
0

當我運行這個程序時,它被卡在一個要求我輸入值的循環中,並繼續添加一個和數。雖然這正是它應該做的事,但如果我輸入一個可以被6或17整除的數字,循環不會結束。可以解釋爲什麼?簡單可分性

import java.util.Scanner;

public class DivisibleBy6or17 { 
    public static void main(String[] args){   
    Scanner in = new Scanner(System.in); 
    System.out.print("Enter Value: "); 
    int one = in.nextInt(); 
    int sum=0; 

    while (one % 6 != 0||one % 17 != 0) { 
     System.out.print("Enter Value: "); 
     one = in.nextInt(); 
     sum++; 
    } 

    System.out.print("Numbers read: " + sum); 
    } 
} 
+1

''|| - >''&& ... – Mysticial

+1

嘗試輸入102 :) –

+0

一個'%6 = 0 ||一個17%= 0'嘗試換!在括號中,因爲很難得到正在發生的事情。也可能泄漏優先級混淆問題 – mishadoff

回答

1

您應該使用 「& &」 而不是 「||」:

while (one % 6 != 0 && one % 17 != 0) { 

你的老狀態僅停止循環,如果,如果整除6和17

0

在數這個條件,你正在使用一個OR;要離開while循環,您必須同時擁有one % 6 == 0one % 17 == 0。如果你輸入102,你應該離開循環。

要修復,請使用&&而不是||

0

條件有錯誤,正確的條件是:

while(!(one % 6 == 0 || one % 17 == 0)) 

while(one % 6 != 0 && one % 17 != 0) 
0

我認爲你將不得不使用Short-Circuit And,而不是OR

while (one % 6 != 0 && one % 17 != 0)

0

這只是一個建議,但你爲什麼不嘗試創建會做你正在嘗試做的,而不是把代碼在main方法的任務的方法。這是爲了實踐可重用性。這裏是我的意思是:

public static void main(String[] args) { 
     //Enter code here 
     //Method Calls here 
     } 
public someMethod here(arguements if needed) 
{ 
    //Body here 
}