Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Q5 {
- /* 請撰寫程式,判斷輸入的整數是否為質數 */
- public static void main(String[] args) {
- Scanner keyboardInput = new Scanner(System.in);
- String numberInput = new String();
- boolean checkPrime = true; //checkPrime:判斷是否為質數
- int temp, checkSum = 0; //temp:存經防呆機制後的輸入數值, checkSum:存字串陣列檢查值
- /* 防呆處理 */
- do { //後測試迴圈,若輸入值不為數字即重新輸入
- System.out.println("請輸入大於零的整數:");
- numberInput = keyboardInput.nextLine(); //得到輸入值
- checkSum = 0;
- for(char i = 0 ; i < numberInput.length() ; i++) { //輸入值檢查迴圈,需知字串其實是陣列,因此檢查長度為陣列大小
- //以字串陣列檢查輸入是否為0~9
- //(以index檢索拆成一個一個字元,再判斷ascii)
- if(((numberInput.charAt(i) >= 48) && (numberInput.charAt(i) <= 57)))
- checkSum++;
- }
- if(checkSum == numberInput.length()) { //當字串陣列都輸入正確時,排除例外情況的機制
- temp = Integer.parseInt(numberInput);
- if(temp == 0) //排除輸入零的情況
- checkSum = 0;
- }
- } while(checkSum != numberInput.length());
- /* 質數判斷 */
- temp = Integer.parseInt(numberInput);
- if(temp == 1) { //1不是質數
- checkPrime = false;
- } else {
- for(int i = 2 ; i < temp ; i++) {
- checkPrime = false;
- if((temp % i) == 0) //一個數在2~(n-1)間可以被整除,即非質數,並跳出迴圈
- break;
- checkPrime = true;
- }
- }
- if(checkPrime) {
- System.out.println(temp + "是質數");
- } else {
- System.out.println(temp + "不是質數");
- }
- }
- }
Add Comment
Please, Sign In to add comment