2012-12-26 15 views
0

我將發佈問題,然後發佈我目前已完成的代碼。我覺得我很接近,但我陷入了一個我似乎無法理解的地方。這裏有:Java:將數字存儲在向量中,傳輸到數組,然後從數組中取數據並存儲到另一個向量中

問題:創建一個存儲N個數字的向量。通過控制檯將N個非負數輸入到數組中。然後創建另一個只存儲N個數字中的M個素數的Vector。

到目前爲止我的代碼:

import java.util.*; 

public class VectorPrimes { 

    public static Vector<Integer> inputVc = new Vector<Integer>(); 
    public static Vector<Integer> primeVc = new Vector<Integer>(inputVc); 

    public static boolean isPrime(int n) { 
     boolean prime = true; 
     for (int i = 2; i * i <= n; i+= 2) { 
      if (n % i == 0) { 
       prime = false; 
       break; 
      } 
     } 

     return prime; 
    } 

    public static void main(String[] args) { 
     Scanner scan = new Scanner(System.in); 
     System.out 
       .println("This program will take input of positive numbers and output" 
         + " prime numbers, if any, from the input numbers."); 

     System.out 
       .println("Input a positive number to check for prime numbers: "); 



     boolean looping = true; 

     while (looping) { 
      System.out 
        .println("Input '0' to finish inputting numbers and print the primes."); 
      String userin = scan.nextLine(); 
      int input = Integer.parseInt(userin); 

      if (input != 0) { 

       System.out.println("Enter next number: "); 

       inputVc.add(input); 
      } else if (input == 0) { 
       //Integer[] inputArray = inputVc.toArray(new Integer[inputVc.size()]); 
       looping = false; 



       System.out.println(inputVc); 
       System.out.print(primeVc); 
       System.exit(0); 
      } 

     } 

    } 
} 

我敢肯定,這不是做的最好的方式,但是這是我到目前爲止所。清楚的是,我無法從輸入矢量(inputVc)中獲取輸入數字進入數組(inputArray),然後將素數存儲在素數矢量(primeVc)中並打印出來。我嘗試了3種或4種不同的方法,但我無法獲得任何存儲在primeVc矢量中的東西,它只是使打印空白。

我不是要求代碼,我試圖弄清楚的是嚴格如何獲得素數輸入primeVc向量然後打印它。當然inputVc數字需要通過isPrime方法運行,然後添加到primeVc向量如果是的話,但我很確定這是我遇到我的問題。

你們看到了什麼?我絕對錯過了一些東西,不能爲我的生活弄清楚。

+0

你確實想用矢量嗎? –

+0

問題是:「創建一個存儲N個數字的向量,通過控制檯向數組中輸入N個非負數......」這個要求規定您需要從控制檯讀入數字並將它們存儲在數組中(閱讀矢量)。在提取素數之前,不需要從Vector複製到數組。只需閱讀每個數字並將其推入Vector。 –

+1

聽起來像我的作業。 – MrSmith42

回答

2

做這樣的事情:

//... 
if (input != 0) { 
    System.out.println("Enter next number: "); 
    inputVc.add(input); 
    if (isPrime(input)) 
     primeVc.add(input); 
} 
//... 

你也可以創建while(true)循環,只是break它時,你會得到0

+0

非常感謝!考慮到我錯過了這麼簡單的事情,我真的應該走開並放鬆一下。聖誕快樂,新年快樂! – SteveM

+0

沒問題。你也是! :)但請考慮你的'isPrime'方法導致它不正確。 – bellum

0

首先你要打電話給你functon isPrime那麼,如果返回值是true,則其添加到您的第二個列表 和其他的東西,你的函數isPrime將無法​​正常工作,你的「i」是2初始值,那麼你正在遞增2,所以它會返回每個奇數的值true

相關問題