import javax.swing.JOptionPane;

/**
 * Ueberprueft Zahlen, ob sie eine Primzahl sind oder nicht
 * @author Martin
 */
public class PrimzahlCheck {

	public static void main(String[] args) {

		while (true) {
			String eingabe = readUserMessage();
			if (eingabe == null) {
				System.exit(0);
			}
			int zahl;
			zahl = Integer.parseInt(eingabe);
			String result;
			if (isPrime(zahl)) {
				result = zahl + " ist eine Primzahl! :)";
			} else {
				result = zahl + " ist keine Primzahl :(";
			}
			showResult(result, "Ergebnis");
		}

	}

	/**
	 * Zeigt einen Dialog zum Zahlen eingeben an
	 */
	public static String readUserMessage() {
		return JOptionPane.showInputDialog(null, "Geben Sie eine Zahl ein",
				"Primzahlcheck", JOptionPane.PLAIN_MESSAGE);
	}

	/**
	 * Zeigt eine Fehlermeldung an
	 * @param message Die Fehlermeldung
	 * @param title Der Titel der Fehlermeldung
	 */
	public static void showError(String message, String title) {
		JOptionPane.showMessageDialog(null, message, title,
				JOptionPane.WARNING_MESSAGE);
	}

	/**
	 * Zeigt eine Ergebnismeldung an
	 * @param message Die Nachricht
	 * @param title Der Titel der Nachricht
	 */
	public static void showResult(String message, String title) {
		JOptionPane.showMessageDialog(null, message, title,
				JOptionPane.INFORMATION_MESSAGE);
	}

	/**
	 * ueberprueft Zahlen, ob diese eine Primnzahl sind
	 * @param n die zu ueberpruefende Zahl
	 * @return true wenn es sich um eine Primzahl handelt, sonst false
	 */
	private static boolean isPrime(int n) {
		if (n < 2) {
			return false;
		}
		boolean isPrime = true;
		for (int i = 2; i * i <= n; i++) {
			if (n % i == 0) {
				isPrime = false;
			}
		}
		return isPrime;
	}

}