Sunday, July 16, 2017

Write a program that accepts a number from the user and tells whether the number is a prime number.

/**
 * Created by Jo on 7/10/2017.
 * For more exercises and lessons, visit http://shegertech.blogspot.com/
 * Chapter 5, Exercise 3
 */

import java.util.Scanner;

public class Q3Solution {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        int num = 0, half = 0;
        boolean flag = false;

        System.out.print("Enter a positive integer number : ");
        num = in.nextInt();
        half = num / 2;
        if (num > 0) {
            for (int i = 2; i <= half; i++) {
                if (num % i == 0) {
                    flag = true;
                }
            }
            if (flag) {
                System.out.println(num + " is not a prime number.");
            } else {
                System.out.println(num + " is a prime number.");
            }
        } else {
            System.out.println("Please enter a non-negative integer number.");
        }
    }
}

Share: