2017-03-23 101 views
1

由於某些原因,當我測試此值時,第二個if語句始終打印出1和1之間的每個數字將用戶輸入編號爲不是素數,即使它是。但是,第三條if語句正確指出用戶的數字是否爲素數。我在做什麼不對?試圖編寫詢問用戶號碼的代碼,確定它是否爲素數,並列出一個號碼與該號碼之間的素數

public static void main(String[] args) { 

    @SuppressWarnings("resource") 
    Scanner input = new Scanner(System.in) ; 

    System.out.println("intput a number") ; 
    int number = input.nextInt() ; 

    int counter = 0 ; 
    int counter2 = 0 ; 

    for (int i = 1 ; i <= number ; i++) { 
     for (int j = 1 ; j <= i ; j++) { 
      if (i % j == 0) { 
       counter ++ ; 
      } 
      else if (i%j != 0) { 
      } 
     } 
     if (counter != 2) { 
      System.out.println(i+" is not prime") ; 
     } 
     if (counter == 2) { 
      System.out.println(i+", is a prime") ; 
     } 
     System.out.println("\n") ; 
     if (number % i == 0) { 
      counter2 ++ ; 
     } 
    } 
    if (counter2 != 2) { 
     System.out.println(number+" is not prime") ; 
    } 
    else if (counter2 == 2){ 
     System.out.println(number+" is a prime") ; 
    } 
} 
+2

* 「列出了數之間的素數」 *哪有之間的任何「 「一個號碼?你不需要兩個數字來表示「之間」有意義嗎? – Andreas

回答

0

您對所有數字都使用相同的計數器,但您沒有重置它,因此計數器的值正在上升。你

int counter; 
int counter2 = 0 ; 

for (int i = 1 ; i <= number ; i++) { 

    //Resets the counter 
    counter = 0 ; 

    for (int j = 1 ; j <= i ; j++) { 
     if (i % j == 0) { 
      counter ++ ; 
     } 
     else if (i%j != 0) { 
     } 
    } 

    //You don't need two if's if one is the negation of the other 
    if (counter != 2) { 
     System.out.println(i+" is not prime") ; 
    } 
    else{ 
     System.out.println(i+", is a prime") ; 
    } 
    System.out.println("\n") ; 
    if (number % i == 0) { 
     counter2 ++ ; 
    } 
} 
//You don't need two if's if one is the negation of the other 
if (counter2 != 2) { 
    System.out.println(number+" is not prime") ; 
} 
else{ 
    System.out.println(number+" is a prime") ; 
} 

也可以避免麻煩,如果你做了isPrime功能來告訴你,如果數字是素與否,它看起來更清潔。

1

你的程序似乎有點過於複雜,爲什麼不只是做一個方法來確定它的prime或不?

例子:

public static boolean isPrime(int number){ 
    if(number <= 1) return false; 
    for (int i = 2; i < number; i++){ 
     if (number % i == 0) return false; 
    } 
    return true; 
} 

main方法裏面,只需調用它像這樣:

Scanner input = new Scanner(System.in) ; 
System.out.println("input a number") ; 
int number = input.nextInt() ; 
for (int i = 1 ; i <= number ; i++) { 
    if(isPrime(i)){ 
     System.out.println(i+" is a prime") ; 
    }else{ 
     System.out.println(i+" is NOT a prime") ; 
    } 
} 
+1

您可以用i <= sqrt(數字)替換i <=數字。在數學上,如果一個數字是素數,它的平方根和1之間將不會有除數。平方根後面的數字是多餘的。 – discipline

+0

在我的計算機科學課程中,我們仍然沒有了解返回和布爾值,所以如果我把它放在我的代碼中生病可能會丟失一些標記或東西 – CheeseHacker

+0

@CheeseHacker沒問題,你沒有提到,因此我認爲你是在做它爲了好玩我猜。 –

相關問題