小编典典

用户输入中不重复数字

java

我正在尝试找出如何创建输入验证的方法,在该方法中,您不能两次输入相同的数字,而且不能在数字范围内输入,除非它是整数,否则无法输入任何内容。我目前正在创建彩票程序,不确定如何执行此操作。任何帮助将非常感激。我的数字范围验证有效,而其他两个验证无效。我尝试了非重复号码验证,但我不确定如何执行仅数字验证。有人可以告诉我如何构建此结构。

此方法在我的Player类中

public void choose() {
        int temp = 0;

        for (int i = 0; i<6; i++) {
            System.out.println("Enter enter a number between 1 & 59");
            temp = keyboard.nextInt();
            keyboard.nextLine();
            while ((temp<1) || (temp>59)) {
                System.out.println("You entered an invalid number, please enter a number between 1 and 59");
                temp = keyboard.nextInt();
                keyboard.nextLine();
            }

            if (i > 0) {
                while(temp == numbers[i-1]) {
                    System.out.println("Please enter a different number as you have already entered this");
                    temp = keyboard.nextInt();
                    keyboard.nextLine();
                }
            }
            numbers[i] = temp;
        }
    }

阅读 213

收藏
2020-11-26

共1个答案

小编典典

如下进行:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static int[] numbers = new int[6];
    static Scanner keyboard = new Scanner(System.in);

    public static void main(String args[]) {
        // Test
        choose();
        System.out.println(Arrays.toString(numbers));
    }

    static void choose() {
        int temp;
        boolean valid;
        for (int i = 0; i < 6; i++) {
            // Check if the integer is in the range of 1 to 59
            do {
                valid = true;
                System.out.print("Enter in an integer (from 1 to 59): ");
                temp = keyboard.nextInt();
                if (temp < 1 || temp > 59) {
                    System.out.println("Error: Invalid integer.");
                    valid = false;
                }
                for (int j = 0; j < i; j++) {
                    if (numbers[j] == temp) {
                        System.out.println("Please enter a different number as you have already entered this");
                        valid = false;
                        break;
                    }
                }
                numbers[i] = temp;
            } while (!valid); // Loop back if the integer is not in the range of 1 to 100
        }
    }
}

运行示例:

Enter in an integer (from 1 to 59): 100
Error: Invalid integer.
Enter in an integer (from 1 to 59): -1
Error: Invalid integer.
Enter in an integer (from 1 to 59): 20
Enter in an integer (from 1 to 59): 0
Error: Invalid integer.
Enter in an integer (from 1 to 59): 4
Enter in an integer (from 1 to 59): 5
Enter in an integer (from 1 to 59): 20
Please enter a different number as you have already entered this
Enter in an integer (from 1 to 59): 25
Enter in an integer (from 1 to 59): 6
Enter in an integer (from 1 to 59): 23
[20, 4, 5, 25, 6, 23]
2020-11-26