Ahmed February 2016

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?

Answers


Celine NOEL February 2016

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.

Post Status

Asked in February 2016
Viewed 3,637 times
Voted 5
Answered 1 times

Search




Leave an answer