2015-09-28 21 views
0

目前即時通訊試圖找到整除的數的用戶輸入和數量應該是可分從X到Y發現divisble的數量從X到Y

例如:2520是由所有的數字整除1-10。

所以這裏是我到目前爲止所做的,很清楚我編碼的方式很糟糕,任何人都可以做得更好?

public static void main (String[] args){ 
    Scanner kb = new Scanner(System.in); 
    int temp = 0,x,y,num; 
    System.out.println("enter the number to check for"); 
    num = kb.nextInt(); 
    System.out.println("enter the starting number"); 
    x = kb.nextInt(); 
    System.out.println("enter the ending number"); 
    y=kb.nextInt(); 

    while(x >= y){ 
     System.out.println("starting num must be less then the ending num,re-enter the starting num."); 
     x = kb.nextInt(); 
     System.out.println(" now enter the ending number, must be greater then the starting num"); 
     y=kb.nextInt(); 
    } 
    while (num % x == 0 && x < y){ 
     x++; 
    } 
    if (x == y){ 
     System.out.println("the number "+ num + " is divisble by this range."); 
    } 
    } 
} 
+3

你是什麼意思,「從x到y均勻可分」? – Michael

+0

你的意思是可以被給定範圍內的每個數字整除嗎? – gla3dr

+0

只是刪除它更清楚,我只是表示所有的數字應該是可分的(餘數應該是0) –

回答

2

寫它作爲一個輔助方法:

public static boolean isDivisibleByAll(int dividend, int fromDivisor, int toDivisor) { 
    for (int divisor = fromDivisor; divisor <= toDivisor; divisor++) 
     if (dividend % divisor != 0) 
      return false; 
    return true; 
} 
+0

驚人的高效。 –

0

有些事情要考慮:

  • 這將是更加人性化,如果你接受任何順序的整數。如果第一個比第二個大,那就從第二個到第一個。所以,像這樣:

    int swapInt; 
    if (x > y) 
    { 
        swapInt = x; 
        x = y; 
        y = swapInt; 
    } 
    
  • 請將您接受的起點和終點相同的整數更加人性化。用戶可能只想檢查一個號碼。 (你會如何改變你的代碼來做到這一點?)

  • 它看起來像你接受任何整數,包括零和負整數。你的程序會繼續工作嗎?如果不是,你需要改變什麼?
+0

爲零和負數生病的情況下,我的問題是,如果人選擇第一個數字作爲相同的數字,我喜歡交換數字的想法。 –

相關問題