1

Hello
I have java project that user need to enter int = number and find prime number.

Problem: When I Enter 10 Does't Print Any Thing.

public class Prime_Numbers {
    
    public static void main(String[] args)
    {
        // Scanner
        Scanner scan = new Scanner(System.in);
        
        // Variables
        int num = 10, i = 2;
        
        // Ask User For Input
        System.out.println("Please Enter Number: ");
        num = scan.nextInt();
        
        while(i <= num/2)
        {
            if(num % i == 2) 
            {
                System.out.println(num);
                break;  
            }
        }
    }
}
Neel Patel
  • 11
  • 3
  • 1
    Infinite loop. Neither `i` nor `num` ever changes within the loop. – Fred Larson Mar 10 '21 at 18:55
  • 1
    `while` loop is infinite because neither `i` nor `num` are changed; with `num = 10` nothing can be printed because `10 % 2 == 0` and condition in `if` is always false. The following question: [...trying to write a code to check if a number is prime...](https://stackoverflow.com/questions/65968558/return-a-boolean-value-using-if-else-in-java/65969133#65969133) has answers how to find a prime number. – Nowhere Man Mar 10 '21 at 18:56

3 Answers3

1

If you look at the if statement inside your while-loop, nothing inside gets executed. The reason is the condition of the if-statement: (num % i == 2). Since 10%2 is not equal to 2, nothing will be printed. Rather, it is equal to 0. If you are trying to check if num is an even number, then change num % i == 2 to num % i == 0.

luk2302
  • 55,258
  • 23
  • 97
  • 137
RW77
  • 64
  • 1
  • 8
0

You can try this code :

import java.util.Scanner;
public class PrimeNumberExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter number : ");
        int number = scanner.nextInt();
        boolean flag = false;
        
        for(int count=2; count<number; count++) {
            if(number%count == 0) {
                flag = true;
                break;
            }
        }
        
        if(!flag) {
            System.out.println(number + " is Prime");
        } else {
            System.out.println(number + " is Not Prime");   
        }   
    }
}
Satyajit Bhatt
  • 211
  • 1
  • 7
0

maybe you can try find prime number code

public class PrimeExample{
     public static void main(String args[]){
          int i,m=0,flag=0;
          int n=5;//it is the number to be checked
          m=n/2;
          if(n==0||n==1){
                System.out.println(n+" is not prime number");
          }else{
           for(i=2;i<=m;i++){
                if(n%i==0){
                    System.out.println(n+" is not prime number");
                    flag=1;
                    break;
                }
           }
           if(flag==0)  {
                System.out.println(n+" is prime number");
            }
      }
}
Asen
  • 1