如何使用生成对复制String向量?
例如,我得到了一个包含三个单词的向量:香蕉,猫和狗。 如何将此向量和单词复制到另一个向量?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 :(得分:0)
您不需要使用while循环来创建0到20之间的随机数:
nrOfWords = in.nextInt(20/*max number*/);
现在你将计算到nrOfWords并将它们添加到String []对中的偏移处;
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)];
}