Guest User

Untitled

a guest
Jul 23rd, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Q5 {
  4. /* 請撰寫程式,判斷輸入的整數是否為質數 */
  5.  
  6. public static void main(String[] args) {
  7. Scanner keyboardInput = new Scanner(System.in);
  8. String numberInput = new String();
  9. boolean checkPrime = true; //checkPrime:判斷是否為質數
  10. int temp, checkSum = 0; //temp:存經防呆機制後的輸入數值, checkSum:存字串陣列檢查值
  11.  
  12. /* 防呆處理 */
  13. do { //後測試迴圈,若輸入值不為數字即重新輸入
  14. System.out.println("請輸入大於零的整數:");
  15. numberInput = keyboardInput.nextLine(); //得到輸入值
  16. checkSum = 0;
  17. for(char i = 0 ; i < numberInput.length() ; i++) { //輸入值檢查迴圈,需知字串其實是陣列,因此檢查長度為陣列大小
  18. //以字串陣列檢查輸入是否為0~9
  19. //(以index檢索拆成一個一個字元,再判斷ascii)
  20. if(((numberInput.charAt(i) >= 48) && (numberInput.charAt(i) <= 57)))
  21. checkSum++;
  22.  
  23. }
  24. if(checkSum == numberInput.length()) { //當字串陣列都輸入正確時,排除例外情況的機制
  25. temp = Integer.parseInt(numberInput);
  26. if(temp == 0) //排除輸入零的情況
  27. checkSum = 0;
  28. }
  29.  
  30. } while(checkSum != numberInput.length());
  31.  
  32. /* 質數判斷 */
  33. temp = Integer.parseInt(numberInput);
  34. if(temp == 1) { //1不是質數
  35. checkPrime = false;
  36. } else {
  37. for(int i = 2 ; i < temp ; i++) {
  38. checkPrime = false;
  39. if((temp % i) == 0) //一個數在2~(n-1)間可以被整除,即非質數,並跳出迴圈
  40. break;
  41. checkPrime = true;
  42. }
  43. }
  44.  
  45. if(checkPrime) {
  46. System.out.println(temp + "是質數");
  47. } else {
  48. System.out.println(temp + "不是質數");
  49. }
  50.  
  51. }
  52.  
  53. }
Add Comment
Please, Sign In to add comment