Non duplicates numbers in user input

前端 未结 5 463
野性不改
野性不改 2021-01-24 02:59

I am trying to work out how to create an input validation where it won\'t let you enter the same number twice as well as being inside a range of numbers and that nothing can be

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-24 03:30

    What you want to do is use recursion so you can ask them to provide input again. You can define choices instead of 6. You can define maxExclusive instead 59 (60 in this case). You can keep track of chosen as a Set of Integer values since Sets can only contain unique non-null values. At the end of each choose call we call choose again with 1 less choice remaining instead of a for loop. At the start of each method call, we check if choices is < 0, if so, we prevent execution.

        public void choose(Scanner keyboard, int choices, int maxExclusive, Set chosen) {
            if (choices <= 0) {
                return;
            }
            System.out.println("Enter enter a number between 1 & " + (maxExclusive - 1));
    
            int value = keyboard.nextInt();
    
            keyboard.nextLine();
    
            if (value < 1 || value >= maxExclusive) {
                System.out.println("You entered an invalid number.");
                choose(keyboard, choices, maxExclusive, chosen);
                return;
            }
    
            if (chosen.contains(value)) {
                System.out.println("You already entered this number.");
                choose(keyboard, choices, maxExclusive, chosen);
                return;
            }
            chosen.add(value);
            choose(keyboard, --choices, maxExclusive, chosen);
        }
    
    
    choose(new Scanner(System.in), 6, 60, new HashSet<>());
    

提交回复
热议问题