2015-02-11 30 views
0

我在爲我的程序找到所有可能的奇數時遇到困難。我需要使用while循環來查找所有的奇數,但我不知道如何打印出來。我不知道如果我在這個塊while((num1+num2)%2==0)做任何錯誤,因爲這只是一個猜測。該計劃的大綱是讓用戶輸入2個數字,是另一個數字的偶數倍。我不確定那部分是如何。找到2個數字是另一個數字的偶數倍後,我應該顯示兩個數字之間的所有奇數。非常感謝提前。獲取用戶輸入中所有可能的奇數

import java.util.Scanner; //imports the java utillity scanner 

public class MyPrompter{ 
    public static void main(String[] args){ 

    System.out.println("Odd number display"); 


    Scanner input = new Scanner(System.in); //scans for user input and stores in "input" 

    int num1,num2; //declares the variables i need for the pgrm 

try{ //try statement to check for user input errors 
    System.out.println("Please enter your first number: "); 
    num1 = input.nextInt(); //stores input for the first number 

    System.out.println("Please enter your second number: "); 
    num2 = input.nextInt(); //stores input for the second number 

    while((num1+num2)%2==0){ //while loop to find all the odd numbers between the 2 numbers 
    System.out.println(); 
    } 
} 
catch(java.util.InputMismatchException e){ //if the above error is met, message will be sent to the user 
       System.out.println("Please enter a valid ROUNDED NUMBER!"); 
     } 
    } 
} 
+1

你猜的代碼實際上是完全廢話(你寫的代碼,我的意思是)。猜測通常不起作用。你對循環有什麼瞭解? – immibis 2015-02-11 00:35:32

+0

沒多少先生,我們剛剛開始。我只有一些簡單的說法,if語句和它的含義。我真的很困惑,如何獲得2個數字是其他數字的偶數,然後顯示所有奇數#。 – reckless 2015-02-11 00:42:01

+0

也許你應該從簡單的事情開始,比如打印一個號碼的程序,或者找到一個數字是另一個數字的倍數。幾點:作爲循環條件(num1和num2)的一部分的變量必須在循環體中改變*,否則循環不能結束。 'System.out.println()'只是打印一個空行,而不是一個數字。 – 2015-02-11 00:47:09

回答

0

怎麼是這樣的:

int num1 = 10; 
    int num2 = 50; 
    int current = num1; 
    while (current < num2) { 
     if (current % 2 != 0) { 
      System.out.println(current); 
     } 
     current++; 
    } 

設置電流等於NUM1,繼續循環,同時電流小於NUM2。對於每次迭代檢查電流是否爲奇數,如果是,則輸出。增加一個電流。

+0

1 = 0是否表示!= 0? – reckless 2015-02-11 00:56:30