http://blog.csdn.net/lwcumt/article/details/8027586
import java.util.Scanner;
//質數又稱素數,是指在一個大於1的自然數中,除了1和此整數自身外,不能被其他自然數整除的數
public class PrimeNumber {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);// 掃描器,接收控制台輸入信息
System.out.print("請輸入一個整數:");
try {
int num = scan.nextInt();// 取出控制台輸入的信息
if (isPrime(num)) {// 調用isPrime()方法
System.out.println(num + "是素數!");// 若isPrime()方法返回true,輸出是素數
} else {
System.out.println(num + "不是素數!");// 若isPrime()方法返回false,輸出不是素數
}
} catch (Exception e) {
System.out.println("請輸入整數");// 捕捉異常,若輸入的不是整數,輸出異常
}
}
/**
* <pre>
* 用於判斷一個數是否為素數,若為素數,返回true,否則返回false
* </pre>
*
* @param a
* 輸入的值
* @return true、false
*/
public static boolean isPrime(int a) {
boolean flag = true;
if (a < 2) {// 素數不小於2
return false;
} else {
for (int i = 2; i <= Math.sqrt(a); i++) {
if (a % i == 0) {// 若能被整除,則說明不是素數,返回false
flag = false;
break;// 跳出循環
}
}
}
return flag;
}
}