我试图编写一个程序来选择要随机管理的团队,但是当我运行它时,我得到的是相同的4个团队,而不是每次都有不同的团队?
我试图做到这一点,以便每次生成随机数时都会将其放入一个数组中,然后针对该数组进行检查以查看该数字是否曾经被使用过。
任何帮助或建议,将不胜感激。谢谢!
import java.util.*;
class Start {
static String[] places = {"Man Utd", "Arsenal", "Aston Villa", "Chelsea",
"Everton", "Fulham", "Liverpool", "Man City", "Newcastle", "Norwich",
"QPR", "Reading", "Southampton", "Stoke", "Sunderland", "Swansea",
"Spurs", "West Brom", "West ham", "Wigan"};
static int[] NA = {21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21};
static Random rand = new Random();
static int RandInt = 0;
static boolean x = false;
static boolean p = false;
static int player = 1;
public static void main(String[] args) {
while (x != true) {
RandInt = rand.nextInt(places.length);
for (int k = 0; k <= NA.length; k++) {
while (p != true) {
if (RandInt == NA[k]) {
RandInt = rand.nextInt(places.length);
} else {
p = true;
NA[k] = RandInt;
}
}
System.out.println("player " + player + " is managing " + places[RandInt]);
player++;
p = false;
if (player >= 5) {
x = true;
System.exit(0);
}
}
}
}
}
我“清理”了一下您的代码,并更改了Array以检查重复的随机数到ArrayList。这不是最快的解决方案,但它应该可以工作。
问题是,直到整个程序退出,您才不会退出for循环。如上所述,geoand,RandInt == NA [k]永远不会为真,因为RandInt始终为<= 19,因此不会生成新的随机数。因此,代码中有两个错误的地方。
当您想了解有关更快检查重复项的更多信息时,也许会对您有所帮助:http : //javarevisited.blogspot.de/2012/02/how-to-check-or-detect-duplicate.html
希望能对您有所帮助。:)
static String[] places = {"Man Utd", "Arsenal", "Aston Villa", "Chelsea",
"Everton", "Fulham", "Liverpool", "Man City", "Newcastle", "Norwich",
"QPR", "Reading", "Southampton", "Stoke", "Sunderland", "Swansea",
"Spurs", "West Brom", "West ham", "Wigan"};
static int[] NA = new ArrayList<Integer>(5);
static Random rand = new Random();
static int RandInt = 0;
static int player = 1;
public static void main(String[] args) {
while (player < 5) {
RandInt = rand.nextInt(places.length);
for (int i = 0; i <= NA.size(); i++) {
if (RandInt == NA.get(i)) {
RandInt = rand.nextInt(places.length);
} else {
NA.add(RandInt);
break;
}
}
System.out.println("player " + player + " is managing " + places[RandInt]);
player++;
}
System.exit(0);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句