如何告诉Java打印随机生成的匹配数字的值。例如,如果输出为3,3,7:系统应该打印出来,"你有两个3"。
int r1 = (int) (Math.random()*6) +1;
int r2 = (int) (Math.random()*6) +1;
int r3 = (int) (Math.random()*6) +1;
System.out.print("Your numbers are " + r1 + r2 + r3);
if (r1 == r2 && r2 ==r3 )
System.out.print(": You got all" + r1 + "'s");
else if (r1 == r2 || r2 == r3 || r1 == r3)
System.out.print(": You got two" + "'s");
else if (r1 != r2 && r2 != r3)
System.out.print(": NO MATCHES!");
else {
}
答案 0 :(得分:2)
使用Collections.frequency
方法处理任意数量的卷的解决方案是:
List<Integer> list = Arrays.asList(roll1, roll2, roll3);
Set<Integer> set = new HashSet<Integer>(list);
for (Integer i : set)
{
System.out.println(i + ": " + Collections.frequency(list, i));
}
将您的卷转换为列表,制作一组(一组没有重复的条目)。
对于集合中的每个值,列表中的值存在的频率。对于卷3, 3, 7
,这将打印:
3: 2
7: 1
答案 1 :(得分:1)
你应该清理你的代码......
您提供的代码无法编译。 逻辑似乎没问题。
package stackoverflow;
public class main {
public static void main(String[] args) {
int r1 = (int) (Math.random()*6) +1;
int r2 = (int) (Math.random()*6) +1;
int r3 = (int) (Math.random()*6) +1;
System.out.print("Your numbers are " + r1 + r2 + r3);
if (r1 == r2 && r2 ==r3 )
System.out.print(": You got all " + r1 + "'s");
else if (r1 == r2 || r2 == r3 || r1 == r3)
System.out.print("numbers: " + r1 + " " + r2 + " " + r3);
else if (r1 != r2 && r1 != r3)
System.out.print(": NO MATCHES!");
else {
}
}
}
这应该基于您给定的代码。
请注意,您正在命名不一致/存在的变量。
答案 2 :(得分:1)
解决方案:将两个数字的随机分配数分成三部分。
int r1 = (int) (Math.random()*6) +1;
int r2 = (int) (Math.random()*6) +1;
int r3 = (int) (Math.random()*6) +1;
System.out.print("Your numbers are " + r1 + r2 + r3);
if (r1 == r2 && r2 ==r3 )
System.out.print(": You got all" + r1 + "'s");
else if (r1 == r2)
System.out.print(": You got two" + r1 + "'s");
else if (r2 == r3)
System.out.print(": You got two" + r2 + "'s");
else if (r1 == r3)
System.out.print(": You got two" + r1 + "'s");
else if (r1 != r2 && r2 != r3)
System.out.print(": NO MATCHES!");
答案 3 :(得分:0)
最简单的事情是
int roll1 = (int) (Math.random()*6) +1;
int roll2 = (int) (Math.random()*6) +1;
int roll3 = (int) (Math.random()*6) +1;
System.out.print("Your numbers are " + roll1 + roll2 + roll3);
if (roll1 == roll2 && roll2 == roll3 )
System.out.print(": You got all" + s1 + "'s");
else if (roll1 == roll2)
System.out.print(": You got two" + roll1 + "'s");
else if (roll2 == roll3)
System.out.print(": You got two" + roll2 + "'s");
else if (roll1 == roll3)
System.out.print(": You got two" + roll1 + "'s");
else
System.out.print(": NO MATCHES!");