Write a java Program which accept number from user and check whether the number is prime or not | EascyCoding45

Write a Java program that accepts numbers from the user and checks whether the number is prime or not.


In this tutorial we are going to learn how we can write a java program which will accept a number from user and check whether it is prime or not.


Program : (Write a java Program which accept number from user and check whether the number is prime or not.)


import java.util.Scanner;


public class PrimeNumber {


    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int number = scanner.nextInt();

        scanner.close();


        if (isPrime(number)) {

            System.out.println(number + " is a prime number.");

        } else {

            System.out.println(number + " is not a prime number.");

        }

    }


    // Function to check if a number is prime

    public static boolean isPrime(int num) {

        if (num <= 1) {

            return false;

        }

        for (int i = 2; i <= Math.sqrt(num); i++) {

            if (num % i == 0) {

                return false;

            }

        }

        return true;

    }

}


Output :

Write a java Program which accept number from user and check whether the number is prime or not | EascyCoding45


Comments