2015-10-14 47 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)]; 
}