Home > other >  Do...while is not working in input verification
Do...while is not working in input verification

Time:05-04

So I'm trying to do an input verification for my program in java, and I'm trying to do that in this setter:

  public void setClientName(String clientName) {
        boolean valid;
        do{
            valid = false;
            try{
                 if(clientName.matches("[a-zA-Z] ")){
                    this.clientName = clientName;
                 }else{
                     throw new IllegalArgumentException("Invalid client name");
                 }
            }catch(Exception e){
                System.out.println("Invalid name");
                valid = true;
            }
        }while(!valid);
    }

But when I call it and put a wrong name, the do...while does not work and the program just continue

Here's where I call it

  public void openAccount(int i){
        nCartao = 2021120040   i;
        System.out.println("Account Number : "   (nCartao));
        System.out.println("Client Name :");

        setClientName(sc.next()); // I CALL IT HERE

        System.out.println("Client Age : ");
        age = sc.nextInt();
        System.out.println("Balance :");
        balance = sc.nextInt();
    }

What am I doing wrong?

CodePudding user response:

Maybe that's because in your catch you are stating that valid is true when it should be false to repeat the block.

  • Related