2015-10-14 48 views
0

如何複製帶有生成配對的字符串向量?如何在內存中生成配對

例如,我得到了一個有三個詞的矢量:香蕉,貓和狗。 我如何複製這個向量和單詞到另一個向量?

String playerOne = null; 
    String playerTwo = null; 
    int nrOfWords = 0; 
    String[] allWords = new String []{"Banana", "Cat", "Book", "Sandwich", "Strawberry", "Milk", "Card", "Computer", "Science", "Java", "Math", "Physics", "Materials", "Phone", "Pencil", "Tv", "Clock", "Shoes", "Jacket", "Gloves"}; 
    String [] pair = null; 
    boolean gameIsOver = false; 


    System.out.print("How many words do you want?(max 20); "); 
    nrOfWords = in.nextInt(); 
    while(nrOfWords < 1 || nrOfWords > 20) 
    { 
     if(nrOfWords > 20) 
     { 
      System.out.print("You have choosen more than 20 words. Please try again:"); 
      nrOfWords = in.nextInt(); 
     } 
     if(nrOfWords < 1) 
     { 
      System.out.print("Error, not a vaild number. Plese Try again."); 
      nrOfWords = in.nextInt(); 
     } 
    } 

    //Create a duplicate of allWords vector with generatePairs. 

回答

0

你不需要while循環在0到20之間創建一個隨機數:

nrOfWords = in.nextInt(20/*max number*/); 

現在,你算截至nrOfWords並在字符串中添加偏移他們[]對;

pair = new String[nrOfWords]; //be sure to initalize or you'll get a NullPointerException 
int index = 0; //set up index var 
for(int counter=0;counter!=nrOfWords;counter++) { 
    pair[index] = allWords[index]; 
    //or pick a random word: 
    //pair[index] = allWords[in.nextInt(allWords.length)]; 
}