javamethodsprimes

To display next N numbers of prime numbers in java


I want to display next n numbers of prime numbers in java

so what i did is accepting the two inputs from user

he enters one number and then he enters the how many next prime numbers to be printed

but i am not getting any output there is no any error

i have created a isprime() which returns true or false if number is prime or not and then in main() i created count variable to display howmany numbers to be printed

import java.util.Scanner;
class NprimeNumbers 
{
    public static boolean isprime(int num)
    {
        int count=0;

        int i;
        for(i=1;i<=num;i++)
        {
            if(num%i==0)
            {
                count++;
            }
        }
        if(count==2)
            return true;
        else
            return false;
    }
    public static void main(String[] args)
    {

        Scanner sc=new Scanner(System.in);

        System.out.println();

        System.out.print("Enter the number : ");
        int number=sc.nextInt();

        System.out.print("How many prime numbers to print : ");
        int hmw=sc.nextInt();

        System.out.println();

        System.out.println("------------------------------OUTPUT------------------------------");

        System.out.println();

        int count=0;           
                
                if(isprime(number))
                {
                    while(count==hmw)
                    {
                        System.out.print(number+",");
                    }
                    count++;
                    number++;
                }
            
            
        

    }
    
}

Output

The output should be 13,17,19,23,27


Solution

  • You can use an iterative for-loop to loop hwm times.

    Within the for-loop, use a while-loop to check isprime with number.

    As a note, in this case, the while-loop doesn't require any enclosing code block, since we'll increase number within the isprime call.
    O'Reilly Media – Java, A Beginner's Guide, 5th Edition – "Loops with no Body".

    for (int count = 1; count <= hmw; count++) {
        while (!isprime(++number));
        System.out.print(number+",");
    }
    

    Here is the input and output.

    Enter the number : 11
    How many prime numbers to print : 5
    
    ------------------------------OUTPUT------------------------------
    
    13,17,19,23,29,