java - 拒绝某些数字的程序

标签 java

我需要创建一个程序,随机打印 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/

相关文章:

java - 使用提要 ://in rome

java - HttpURLConnection 随机延迟

java - 为什么这种泛型方法的重写适用于 1.6 而不是 1.7?

java - 接收java.sql.SQLException : Invalid column index error while invoking database function

java - radio 中的 Wicket 口本地模型

java - eclipse spring 中正确的文件路径是什么

java - 在 java 中将 long 转换为 string 并将 string 转换为 long

java - 动画两个固定点之间的平移 (Libgdx)

java - 检查 GPS 状态时无法停止 Activity

java - 比较一组数组或值列表的最快方法