[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/ProjectRipo/basic-programs/master/java/PrimeCheck.java [Back]  [Original]

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 * To check whether a given number is prime
 */
public class PrimeCheck {

    public static void main(String[] args) {

        // Accept input from the console
        System.out.print("Please enter a natural number: ");
        int num = 0;
        try {
            Scanner sc = new Scanner(System.in);
            num = sc.nextInt();
            sc.close();
        } catch (InputMismatchException e) {
            outputAndEnd("Input not valid, expected a natural number."); // Error message for all non numerical inputs
        }

        if (num < 0) {
            outputAndEnd("Input not valid, natural number expected"); // Error message for all negative inputs
        } else if (num < 2) {
            outputAndEnd("0 and 1 are neither prime nor composite"); // Info message for 0 and 1
        }

        // Check if the given number is divisible from any number between 2 and num/2, if so, its composite
        for (int i = 2; i 

Web Proxy Viewer  |  New URL  |  Original Page