简体   繁体   中英

How can I make a program which ask the user to enter number of limit odd number?

For example, if I enter 5, then the first 5 odd numbers will be shown, like 1,3,5,7,9.

import java.util.Scanner;

/**
 *
 * @author Hameed_Khan
 */
public class JavaApplication20 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner obj=new Scanner(System.in);
        int i;
        System.out.println("Enter limit of ODD num");
        i=obj.nextInt();
                for(int n=0;n<10;n++){
                    if(n%2!=0){
                        int count=n;
                        while(count!=i)
                        System.out.print("\t"+n);
                        n++;
                    }

                }

    }
}

If I understand your question, I'd suggest a simple for loop.

int limit = (what ever user input you use);
int oddNums = 1;
for(int ii = 0; ii < limit; ii++ )
    {
    System.out.println(oddNums);
    oddNums += 2;
    }

Here you go.

import java.util.Scanner;
public class JavaApplication20 {
    public static void main(String args[]) {
        System.out.println("Enter an integer");
        Scanner in = new Scanner(System.in);
        int count = in.nextInt();
        for(int i =1, j=1 ; i <= count ; j+=2,i++){
            System.out.print(j); 
            if(i < count) System.out.print(",");
        }
    }
}

Hope you understand whats happening with the loop and the 2 variables. Here i control the no. of iterations ie equal to the integer entered by the user and j is used to store the value of the odd number and is always incremented by 2 to get the next odd number.

Try its as:

public class JavaApplication20 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
{
    Scanner obj=new Scanner(System.in);
   int i,count=0;
   System.out.println("Enter limit of ODD num");
   i=obj.nextInt();
           for(int n=0;;n++)
           {
               if(n%2!=0 && count!=i)
               {          
                       System.out.print("\t"+n);
                       count++;
               }

           }

}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM