1

Как лучше всего сделать, чтобы нельзя было вводить одинаковые цифры при вводе?

public int fiveNumbers = 1;
public String[] nForBingo = new String[5];
public int[] randomNumbersBingo = new int[70];
public boolean win = false;
public int i = 0;
public int chooseNumber = 0;
public int j = 0;
public boolean checkCreatedBingo = false;
public int numbersInBrackets = 0;
public int allNumbers = 0;
public int option;

public void run() {
    while (!win) {
        BINGO();

    }
}

public int BINGO() {
    System.out.println(
                         "\n************************ * BINGO ************************\n" +
                    "* 1) Create a Bingo card\n" +
                    "* 2) Draw a number\n" +
                    "* 3) Check Bingo card\n" +
                    "* 9) Exit \n*********************************************************");
    if (option == 9) {
        win = true;
        return -1;
    }
    System.out.print("Select a menu option: ");
    option = scan.nextInt();
    if (option == 1) {
        return createBingo();
    } else if (option == 2) {
        return drawNumber();
    } else if (option == 3) {
        return checkBingoCard();
    } else if (option == 9) {
        win = true;
        return -1;
    }

    return BINGO();
}

public int createBingo() {

    for (; i < nForBingo.length; ) {
        System.out.print("Enter a value for field " + fiveNumbers + ": ");
        nForBingo[i] = scan.next();
        if (chooseNumber > 20) {
            System.out.println("The entered value is too high! All values must be between 0 and 20.");
            return createBingo();
        } else if (chooseNumber < 0) {
            System.out.println("The entered value is too low! All values must be between 0 and 20.");
            return createBingo();
        } else {
            i++;
            fiveNumbers++;

        }
    }
    checkCreatedBingo = true;
    return BINGO();
}

public int drawNumber() {
    if (!checkCreatedBingo) {
        System.out.println("You must first create a Bingo card before drawing a number!");
        return BINGO();
    } else {
        randomNumbersBingo[j] = ((int) (Math.random() * 20));
        System.out.println("A number is drawn! The ball reads the number: " + randomNumbersBingo[j] + "!");
        System.out.print("[");
        for (i = 0; i < nForBingo.length; i++) {

            if (nForBingo[i].equals(String.valueOf(randomNumbersBingo[j]))) {
                numbersInBrackets++;
                nForBingo[i] = "(" + nForBingo[i] + ")";
            }

            System.out.print(nForBingo[i]);
            if (i < 4) {
                System.out.print(", ");
            }

        }
        System.out.println("]");
        allNumbers++;
        if (numbersInBrackets == 5) {
            System.out.println("BINGO! All numbers are marked in " + allNumbers + " turns.");
            option = 9;

            return BINGO();
        }
        return BINGO();
    }
}

public int checkBingoCard() {
    if (checkCreatedBingo) {
        System.out.print("Your Bingo cart: [ ");
        for (int j = 0; j < 5; j++) {
            System.out.print(randomNumbersBingo[j]);
            if (j < 4) {
                System.out.print(", ");
            }
        }
        System.out.println(" ]");
        if (numbersInBrackets != 4) {
            System.out.println("Unfortunately you don’t have Bingo card yet!");
        } else if (numbersInBrackets == 4) {
            System.out.println("BINGO! All numbers are marked in " + allNumbers + " turns.");
        }
    }else {

        System.out.println("You must first create a Bingo card!");

    }
    return BINGO();
}
1
  • как лучше всего сделать чтобы нельзя было вводить одинаковые цыфры при вооде
    – Oleh Kozub
    27 окт 2016 в 0:26

2 ответа 2

4

Вам потребуется хранить в некоторой структуре введенные цифры. Эффективней всего будет использовать Set (множество) из Java Collections API. В двух словах, интерфейс Set хранит в себе уникальные элементы и позволяет производить операции добавления\удаления\проверки на существование крайне быстро (в зависимости от реализации). Примеры:

//Создаём новое множество и инициализируем стартовыми значениями.
//Т. к. множество хранит лишь уникальные значения, в set будут содержаться {1, 2, 3, 4, 5}
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 2));

System.out.println(set.contains(3));//Проверяем, содержиться ли значение в множестве
System.out.println(set.contains(6));

Из плюсов такого решения: простота использования и скорость. Из минусов: большой оверхед по памяти.

0

Можно создать массив с значениями которые уже ввел. И перед вводом нового проверять: есть ли такое число в массиве. Если есть, то ищем новое число. Иначе, кладем значение в наш массив и продолжаем логику программы.

1
  • Set рациональнее
    – user31238
    27 окт 2016 в 7:34

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.