我目前正試圖讓我的java程序打印出來不打印出重複的法律。該軟件是隨機挑選打印1至3法律,但我不想重複。我對java還是一個新手,到目前爲止只寫了一些程序。這是迄今爲止我寫的最複雜的一個。hashset刪除數組Java中的重複項
現在我想要軟件再次運行該隨機,如果它發現重複,直到打印中沒有重複。有沒有辦法做到這一點?
/**
*Seeds is a random number to pick which if statement will be used.
* telling the software how many laws to use during its random
* generation process
*
*/
Random seeds = new Random();
seed = seeds.nextInt(3) + 1;
if (seed == 1){
/**Beginning of random law selection for universe. Must find way
*Must find way to get rid of duplicate answers
*/
final String[] Laws = {"Standard Physics", "Magic", "Mad Science",
"Psionics", "Substandard Physics","Exotic"};
Random random = new Random();
int index = random.nextInt(Laws.length);
System.out.println("Law:" + Laws[index]);
}
else if (seed == 2) {
final String[] Laws = {"Standard Physics", "Magic", "Mad Science",
"Psionics", "Substandard Physics","Exotic"};
Random random = new Random();
int index = random.nextInt(Laws.length);
int index2 = random.nextInt(Laws.length);
System.out.println("Law:" + Laws[index] + "," + Laws[index2]);
}
else {
final String[] Laws = {"Standard Physics", "Magic", "Mad Science",
"Psionics", "Substandard Physics","Exotic"};
Random random = new Random();
int index = random.nextInt(Laws.length);
int index2 = random.nextInt(Laws.length);
int index3 = random.nextInt(Laws.length);
System.out.println("Law: " + Laws[index] + "," + Laws[index2] +
"," + Laws[index3]);
}
更少的代碼行,更少的問題,同一個String數組的3個聲明不好,聲明一次,如果其他塊 –