Ahmed
Ahmed

Reputation: 79

Why does it not display Exception error

      List<String> AccountList = new ArrayList<String>(); 
      AccountList.add("45678690");
      AccountList.add("7878787");
      Scanner AccountInput = new Scanner(System.in);
      int x = 1;
 do{
     try{ 

      System.out.println("Hi whats your pin code?");
      String Value = AccountInput.nextLine();

      for  (int counter = 0; counter < AccountList.size(); counter++){  
          if (AccountList.contains(Value)){ //If Input = ArrayList number then display "hi"
              System.out.println("Hi");

              x = 2;
          }

          }

} catch (Exception e){
    System.out.println("You cant do that");

}
}while (x==1); 
      }
}  

When I run this the error "You cant do that" does not appear but it is taken invalid and asks user to re enter number untill valid, how can I get the error line to be displayed?

Upvotes: 1

Views: 29

Answers (1)

Celine NOEL
Celine NOEL

Reputation: 155

You need to throw an exception to be able to catch one:

for  (int counter = 0; counter < AccountList.size(); counter++){  
    if (AccountList.contains(Value)) { //If Input = ArrayList number then display "hi"
        System.out.println("Hi");
        x = 2;
    } else {
        throw new Exception();
    }
}

EDIT: As said in the comment, the for line is not necessary as the algorithm to know if the value is contained in your AccountList is handled by the contains method.

Upvotes: 1

Related Questions