有人可以好心帮助我吗?提前致谢...
下面的代码将字符串输出为重复项。我不想使用 Sets 或 ArrayList。我正在使用 java.util.Random。我正在尝试编写一个代码来检查字符串是否已随机输出,如果是,则不会显示。我哪里出了问题以及如何解决这个问题。
public class Worldcountries
{
private static Random nums = new Random();
private static String[] countries =
{
"America", "Candada", "Chile", "Argentina"
};
public static int Dice()
{
return (generator.nums.nextInt(6) + 1);
}
public String randomCounties()
{
String aTemp = " ";
int numOfTimes = Dice();
int dup = 0;
for(int i=0 ; i<numOfTimes; i++)
{
// I think it's in the if statement where I am going wrong.
if (!countries[i].equals(countries[i]))
{
i = i + 1;
}
else
{
dup--;
}
// and maybe here
aTemp = aTemp + countries[nums.nextInt(countries.length)];
aTemp = aTemp + ",";
}
return aTemp;
}
}
所以我得到的(随机)输出是“美国,美国,智利”,而它应该是“美国,智利”。
最佳答案
您预计什么时候这是错误的?
countries[i].equals(countries[i])
编辑:
这是一个骨架解决方案。我将把辅助方法的填写留给您。
public String[] countries;
public boolean contains(String[] arr, String value) {
//return true if value is already in arr, false otherwise
}
public String chooseRandomCountry() {
//chooses a random country from countries
}
//...
int diceRoll = rollDice();
String[] selection = new String[diceRoll];
for ( int i = 0; i < selection.length; i++ ) {
while (true) {
String randomCountry = chooseRandomCountry();
if ( !contains(selection, randomCountry ) {
selection[i] = randomCountry;
break;
}
}
}
//...then build the string here
这不会检查重要的事情,例如唯一国家/地区
的数量。
关于java - 获取重复的数组输出 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3054532/