Home > Software engineering >  for loop returns only the first data
for loop returns only the first data

Time:12-25

I am trying to loop through my database and returns all the data. The query returns all the data in the database but when I try to loop through it one after the other, it only check the first data and then terminate even when the second or third data might be true. I don't know the error that I made.

         public List<CardType> getAllAvailableCardType(){
                List<CardType> cardTypeList = cardTypeRepository.findAll();
                //this method returns a list of all the cardType from the db
                //and it's working perfectly
                return cardTypeList;
            }
            public void getCards(String cardType) throws DataNotFoundException {
                String cardName = "";
                List<CardType> cardTypeList = getAllAvailableCardType();
                for (CardType cardTypes: cardTypeList){
                    //loop through the list
                    if (cardType.equalsIgnoreCase(cardTypes.getCardTypeName())){
                        //check if the entered string correspond with any of the cardTypeName in the db
                        //I have upto five cardNames stored in my db
                        //if it's true, log it in a console else through the other exception
                        
                        log.info("Congrats, there is card with the entered name " cardType);
                    }
                    throw new DataNotFoundException("There is no card with such name");
                }
                //the problem I am facing is that this doesn't loop through my db
                //it only check if the condition is true or not only on the first data in the db
        
            }

CodePudding user response:

I believe its because you are throwing a datanotfound exception inside the loop, so after the first check in the IF statement if not met then it will go to the last line in the loop which is throw an exception, try the below refactored code

public void getCards(String cardType) throws DataNotFoundException {
    String cardName = "";
    List<CardType> cardTypeList = getAllAvailableCardType();
    boolean found = false;
    for (CardType cardTypes: cardTypeList){
        //loop through the list
        if (cardType.equalsIgnoreCase(cardTypes.getCardTypeName())){
            //check if the entered string correspond with any of the cardTypeName in the db
            //I have upto five cardNames stored in my db
            //if it's true, log it in a console else through the other exception
            log.info("Congrats, there is card with the entered name " cardType);
            found = true;
            break;
        }
    }
    if (!found) {
        throw new DataNotFoundException("There is no card with such name");
    }
}
  • Related