有人可以善良并帮助我在这里.提前致谢...
我的代码在下面输出字符串作为重复.我不想使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我得到(随机)的输出是"美国,美国,智利"应该是"美国,智利".
你什么时候认为这是假的?
countries[i].equals(countries[i])
Run Code Online (Sandbox Code Playgroud)
编辑:
这是一个骨架解决方案.我将为您填写辅助方法.
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
Run Code Online (Sandbox Code Playgroud)
这不会检查重要的事情,比如唯一的数量countries.
| 归档时间: |
|
| 查看次数: |
401 次 |
| 最近记录: |