2014-10-06 13 views
0

我一直在試圖推動複合發電機沿着素數發生器工作,但我似乎無法弄清楚如何使用它。每當我將另一節應用於if (isPrime) { count++;下的代碼時,我會得到一個else如果沒有統計,則整個程序停止工作。對我的問題有任何建議?我如何製作一個複合發電機,輸出的方式與主發電機一樣?

package primegenerator; 
import java.util.Scanner; 

public class PrimeGenerator{ 
public static void main(String[] args) { 
    Scanner input=new Scanner(System.in); 
    double user;`enter code here` 
    System.out.print(" Enter any number: "); 
    user = input.nextDouble(); 
    //Saving user's input for generator 
    final int NUMBER_OF_PRIMES_PER_LINE = 10; //Display 10 per line 
    int count = 0; 
    int number = 2; 

    System.out.println("Your Prime numbers are: \n"); 

    //Reapeatedly find prime numbers 
    while (count < user) { 
     //Assume the number is prime 
     boolean isPrime = true; // Is the current number prime? 

     //Test whether number is prime 
     for (int divisor = 2; divisor <= number/2; divisor++) { 
      if (number % divisor == 0) { //If true, number is not prime 
       isPrime = false; //Set isPrime to false 
       break; //Exit the for loop 
      } 
     } 

     //Display the Prime number and increase the count 
     if (isPrime) { 
      count++; // Increase the count 

      if (count % NUMBER_OF_PRIMES_PER_LINE == 0) { 
       //Display the number and advance to the new line 
       System.out.println(number); 
      //Displays all primes by 10 a line 
      } 
      else 
       System.out.print(number + " "); 

      } 
      //Check if the next number is prime 
      number++; 
     } 
    } 

} 

回答

0

可以System.out.println("Your Prime numbers are: \n");代碼重複到while循環的結束,而是改變你的if(isPrime)if(!isPrime)

我不建議的原因是因爲你,然後通過循環所有的數字都是兩次,並且複製了許多應該真正在自己的方法中的代碼。

如果您知道如何使用List(),您可以在測試數字是否爲素數後,將所有質數添加到一個列表以及將所有素數添加到另一個列表。然後擔心在列表中循環顯示每個列表的數字。

該方法的缺點是,如果用戶輸入的數量非常大,則可能會出現大量內存使用情況。

如果無論您是首先顯示覆合材料還是素數,我都會按照以下方法進行組合。

//Get user number 
while (count < user) 
{ 
    if (!isPrime(count)) //isPrime should be another method similar to your for loop which returns either true or false. 
    { 
     //Print the number, it is composite. 
    } 
    else 
    { 
     //save the number to a List of primes 
    } 
} 

//Print out all the primes saved in the List 
+0

我讓它產生所有的素數,當你問它,但我無法形成我需要使用的代碼,以允許程序生成複合材料以及素數,但在不同的列表中。 – 2014-10-06 17:56:32