gpt4 book ai didi

java - 彩票程序 Java 比较两个数字

转载 作者:行者123 更新时间:2023-12-01 23:57:42 27 4
gpt4 key购买 nike

所以基本上我正在使用两个树集编写一个彩票程序,每个树集有 6 个整数,一个用户输入,另一个随机生成。我必须将这些数字相互比较才能输出奖品,例如,如果两个数字匹配,那么您将赢得 100 美元。我在如何创建这样的方法方面遇到了麻烦。任何帮助将非常感谢!

这是我的主要部分,

public static void main(String[] args)
{
Set<Integer>s1 = createWinningNumber();
Set<Integer>s2 = getUserNumber();

System.out.println("Your ticket was: "+s2);
System.out.println("Winning numbers: "+s1);

}//End of main
public static Set<Integer> getUserNumber()
{
int set = 0;
Set<Integer> number = new TreeSet<Integer>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Pick your Lucky Lotto Numbers");
System.out.print("Type 6 lotto numbers: ");
for(int i = 0; i< 6;i++)
{
System.out.print("");
set = keyboard.nextInt();
number.add(set);
}
return number;
}//End of getUserNumber

public static Set<Integer> createWinningNumber()
{
Set<Integer> winning = new TreeSet<Integer>();
Random generator = new Random();
for(int i = 0;i<6;i++)
{
winning.add(generator.nextInt(40));
}
return winning;
}//End of createWinningNumber

到目前为止的输出

Pick your Lucky Lotto Numbers
Type 6 lotto numbers: 4 12 7 35 20 1
Your ticket was: [1, 4, 7, 12, 20, 35]
Winning numbers: [5, 8, 19, 24, 32]

最佳答案

Set 是正确的选择。不错的选择。

您正在寻找的操作是两个集合的交集。在 Java 中,其实现如下:

s1.retainAll(s2);

s1 现在将仅包含 s2的元素。

然后您可以使用s1.size()来计算常见数字的数量:

public static void main(String[] args)
{
Set<Integer>s1 = createWinningNumber();
Set<Integer>s2 = getUserNumber();

System.out.println("Your ticket was: "+s2);
System.out.println("Winning numbers: "+s1);

s1.retainAll(s2); // s1 contains the intersection of previous s1 and s2
System.out.println("You had " + s1.size() +
" numbers in common with the winning number.");
}

编辑:如果您想保留原始集,请尝试以下操作:

Set<Integer> s3 = new Set<Integer>(s1); // copy s1
s3.retainAll(s2);

关于java - 彩票程序 Java 比较两个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15327496/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com