Search code examples
javaalgorithmnumbersbluej

Prime Number Programme not working


I wanted to create a programme that would display the prime number where the index of the prime number is inputted by the user. Basically the nth prime number would be displayed where n is inputted by the user. The programme however is not working, and any help will be greatly appreciated. The code is written below, could anyone tell me whats wrong with it?

import java.io.*;
public class Nth_Prime
{
    public static void main()throws Exception
    {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Which Prime number would you like to find?");
        int n = Integer.parseInt(stdin.readLine());
        int k = 0;
        int counter = 1;
        int num=0;

    for(int i=3;i<100;i++)
    {
        k=0;
        for(int j=2;j<i;j++)
        {
            if(i%j!=0)
            {
                k++;
            }
        }    
        if(k!=0)
        {
            num=i;
            counter++;
        }
        if(counter==n)


           {
                System.out.println("The number is: "+num);
                break;
            }
        }

    }
}

Solution

  • I got my mistake

        import java.io.*;
    public class Nth_Prime
    {
        public static void main()throws Exception
        {
            BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Which Prime number would you like to find?");
            int n = Integer.parseInt(stdin.readLine());
            int k = 0;
            int checker = 0;
            int counter = 1;
            int num=0;
    
            for(int i=3;;i++)
            {
                k=0;
                checker=0;
                for(int j=2;j<i;j++)
                {
                    if(i%j==0)
                    {
                        checker++;
                    }
                }    
    
                if(checker==0)
                {
                    k++;
                }
                if(k!=0)
                {
                    num=i;
                    counter++;
                }
                if(counter==n)
                {
                    System.out.println("The number is: "+num);
                    break;
                }
                else
                {
                    continue;
                }
            }
    
        }
    }
    

    This is working, but thanks for your help guys