我查看了网站,看到了类似的帖子,但需要进一步澄清。像往常一样,Java新手并想要一些帮助。该场景是乐透计划。将数字输入数组1,数组2生成随机数。将输入与随机数组进行比较。目前坚持将我的输入与随机数组进行比较,并打印出多少数字是正确的。任何帮助,将不胜感激。谢谢。
public class Lotto {
public static void main(String[] args) {
{
Scanner input = new Scanner(System.in);
boolean isNumber;
int[] numbers = new int[6];
{
System.out.println("Please enter number: ");
do{
if (input.hasNextInt())
{
System.out.println("Please enter number: ");
for (int h = 0; h < 5; h++)
numbers[h] = input.nextInt();
isNumber = true;
} else
{
System.out.println("Not a valid input!");
isNumber = false;
input.next();
}
} while (!(isNumber));
for (int h = 0; h < numbers.length; h++)
System.out.print(numbers[h] + " ");
{
int[] lottery = new int[6];
int randomNum;
for (int i = 0; i < 6; i++)
{
randomNum = (int) (Math.random() * 50);
for (int x = 0; x < i; x++)
{
if (lottery[i] == randomNum)
{
randomNum = (int) (Math.random() * 50);
}
}
lottery[i] = randomNum;
}
for (int i = 0; i < lottery.length; i++)
System.out.print(lottery[i] + " ");
}
}
}
}
}
答案 0 :(得分:0)
将此代码添加到最后:
for (int i = 0; i < numbers.length; i++) {
for (int j = i; j < lottery.length; j++) {
if (numbers[i] == lottery[j]) {
counter++;
}
}
}
System.out.println("\n" + counter);
将第一个for循环从for (int h = 0; h < 5; h++)
更改为for (int h = 0; h <= 5; h++)
并创建计数器变量