Non duplicates numbers in user input

前端 未结 5 468
野性不改
野性不改 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:14

    I hope it will help , upvote if yes

    import java.util.ArrayList;
    import java.util.Scanner;
    public class Test {
    private ArrayList choose() {
    Scanner scanner = new Scanner(System.in);
    ArrayList alreadyEntered = new ArrayList<>(6); // using six because your loop indicated me that you're taking six digits 
    for(int i = 0 ; i < 6 ; ++i){ // ++i is more efficient than i++
        System.out.println("Enter a number between 1 & 59");
        String digit;
        digit = scanner.nextLine().trim();
        if(digit.matches("[1-5][0-9]|[0-9]" && !alreadyEntered.contains(digit))// it checks if it is a number as well as if it is in range as well if it is not already entered, to understand this learn about regular expressions
        alreadyEntered.add(digit);
        else {
          System.out.println("Invalid input, try again");
          --i;
        }
     }
     return alreadyEntered // return or do whatever with the numbers as i am using return type in method definition i am returning
    }
    
     scanner.close();
     } 
    

    using arraylist of string just to make things easy otherwise i would have to to some parsing from integer to string and string to integer

提交回复
热议问题