我需要使用布尔数组为类创建一个随机的彩票生成器。起初我使用int数组并且它工作得很好但是当我将int数组更改为bool数组时,我得到一个错误,上面写着“类型不匹配:无法从int转换为boolean”。我想知道如何修复我的代码所以这将工作。
int highestNumber, numsInLottery, randomNum;
//int[] lottery = new int[numsInLottery];
System.out.println("Welcome to the Lottery Number Generator!");
System.out.println("How many numbers are in your lottery?");
numsInLottery = TextIO.getInt();
System.out.println("What is the highest number in your lottery?");
highestNumber = TextIO.getInt();
boolean[] lottery = new boolean[numsInLottery];
for(int i = 0; i < numsInLottery; i++)
{
randomNum = (int)(Math.random() * highestNumber);
for(int x = 0; x < i; x++ )
{
/*if (lottery[x] == randomNum)
{
randomNum = (int)(Math.random() * highestNumber);
x = -1;
}*/
}
lottery[i] = randomNum;
System.out.print(lottery[i] + " ");
}
//System.out.print(lottery[i] + " ");
}
}
你正在为你的乐透[i]分配一个int
lottery[i] = randomNum;
另一种方法是保留int数组,或者说
lottery[i] = randomNum>(highestNumber/2);
所以你有一个布尔值而不是你的整数
假设您的布尔数组在随机索引处具有true
和false
值,您只需检查以下条件:
for(int x = 0; x < i; x++ ){
if(lottery[x]){
randomNum = (int)(Math.random() * highestNumber);
x = -1;
}
}