2015-04-04 116 views
2

我正在編寫一個程序,要求用戶輸入總共十個不同時間的兩個整數。第一個數字是第二個數字的倍數

接下來程序需要評估第一個整數是否是第二個整數的倍數。

如果第一個是第二個的倍數,那麼程序應該輸出「true」,如果不是那麼它應該打印出「false」。

這裏是我的代碼:

 public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 

     int counter = 0; // Initializes the counter 

     System.out.printf("Enter first integer: "); // asks the user for the first integer 
     int number1 = input.nextInt(); // stores users input for the first integer 

     System.out.printf("Enter second integer: "); // asks the user for the second integer 
     int number2 = input.nextInt(); // stores the users input for the second integer 

     while (counter <= 10) // starts a loop that goes to 10 
     { 
      if (number1 & number2 == 0) // checks to see if number1 is a multiple of number2 
       System.out.print("true"); // if so then print out "true" 
      else 
       System.out.print("false"); // otherwise print out "false" 
     } 

    } // end class 

某處沿着我的代碼是打破了線。有沒有人能夠幫助,或者至少讓我指向正確的方向?

+2

使用'%'而不是'&'來檢查number1是否是number2的倍數。 – 2015-04-04 20:54:18

回答

3

您需要閱讀兩個輸入10次。並測試number1number2的倍數。類似於

public static void main(String str[]) throws IOException { 
    Scanner input = new Scanner(System.in); 

    for (int counter = 0; counter < 10; counter++) { 
     System.out.printf("Enter first integer for counter %d: ", counter); 
     int number1 = input.nextInt(); 

     System.out.printf("Enter second integer for counter %d: ", counter); 
     int number2 = input.nextInt(); 

     // Since you want to print true if number1 is a multiple of number2. 
     System.out.println(number1 % number2 == 0); 
    } 
} 
1

&是按位邏輯與功能。我很確定這不會做你想做的事情。似乎你想要MODULO運營商,%

E.g.使用number1%number2。而不是NUMBER1 & NUMBER2

 while (counter <= 10) // starts a loop that goes to 10 
    { 
     if (number1 % number2 == 0) // checks to see if number1 is a multiple of number2 
     System.out.print("true"); // if so then print out "true" 

     else 
     System.out.print("false"); // otherwise print out "false" 
    } 
+0

這是對的;然而,現在我需要程序循環十次並打印出「真」或「假」。 – justLearning 2015-04-04 20:56:41

相關問題