gpt4 book ai didi

java - 拒绝某些数字的程序

转载 作者:行者123 更新时间:2023-12-02 02:50:45 26 4
gpt4 key购买 nike

我需要创建一个程序,随机打印 1 到 42 之间的 6 个数字,其中没有 2 个数字是相同的。用户还必须插入 6 个数字。如果有一个数字与计算机随机选择的数字相同,则计算机必须将其打印出来。如果没有,电脑就会显示你是个失败者。现在的问题是我不确定如何确保没有两个随机选择的数字是相同的。如果数字小于 1、大于 42 或等于先前插入的数字,程序还应该要求不同的数字,并扫描它,但我也无法做到。 (用户不能输入2个相同的数字)

import java.util.Scanner;
import java.util.Random;

public class LotoMachine {

public static void main(String[] args) {

System.out.println("Please enter 6 numbers between 1 and 42.");
Scanner scan = new Scanner(System.in);

int[] marks = new int[6];
Random ran = new Random();
int[] x = new int[6];
boolean winner = false;

for (int i = 0; i < 6; i++) {
marks[i] = scan.nextInt();
while (marks[i] > 42) {
System.out.println(marks[i] + " is out of range. Please pick a number that is less than 43.");
marks[i] = scan.nextInt();
i=0;

}
while (marks[i] < 1) {
System.out.println(marks[i] + " is out of range. Please pick a number that is greater than 0.");
marks[i] = scan.nextInt();
i=0;
}
while (marks[i] == marks[i] - 1) {
System.out.println("You have already chosen " + marks[i] + "Please pick a different number.");
marks[i] = scan.nextInt();
i=0;

}
}
for (int j = 0; j < 6; j++) {
x[j] = ran.nextInt(42) + 1;
for (int y = 0; y < j; y++) {
if (x[j] == x[y]) {
x[j] = ran.nextInt(42) + 1;
j = 0;

}
}
}
System.out.print("You chose");
for (int m = 0; m < 6; m++) {
System.out.print(" " + marks[m]);
}
System.out.println(" ");
System.out.print("The random numbers are");
for (int m = 0; m < 6; m++) {
System.out.print(" " + x[m]);
}
System.out.println(" ");
System.out.print("The number(s) that matched are");
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
if (marks[i] == x[j]) {
winner = true;
System.out.print(" " + marks[i]);
}
}
}
if (winner != true) {
System.out.println("You are such a loser");

}
}

}

最佳答案

可以使用Set来存储值并询问相加后的大小。每当您想要处理不应重复的对象集合时,Set 都是一个好方法,因为它不允许重复。像这样的事情:

Set<Integer> numbers = new HashSet<Integer>();

random code goes here...

int size = numbers.size();
numbers.add(newValue);
if(numbers.size() == size){
number needs to be created again...
}

关于java - 拒绝某些数字的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43873089/

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