Java for循环仅校验第一条数据即终止的问题求助
问题原因
你的代码里,throw new DataNotFoundException放在了for循环的每次迭代逻辑末尾——不管当前遍历到的元素是否匹配输入的cardType,循环执行完第一次后都会直接抛出异常,导致方法终止,根本没机会遍历后续的元素。
修复方案
调整逻辑:只有遍历完整个列表、所有元素都不匹配时,才抛出异常;找到匹配元素时,打印日志后直接结束方法即可。
修复后的代码:
public List<CardType> getAllAvailableCardType(){ List<CardType> cardTypeList = cardTypeRepository.findAll(); //此方法从数据库返回所有CardType列表,运行正常 return cardTypeList; } public void getCards(String cardType) throws DataNotFoundException { List<CardType> cardTypeList = getAllAvailableCardType(); for (CardType cardTypes: cardTypeList){ //遍历列表 if (cardType.equalsIgnoreCase(cardTypes.getCardTypeName())){ //校验输入字符串是否匹配数据库中的cardTypeName log.info("恭喜,存在输入名称对应的卡种 "+cardType); //找到匹配项,直接返回终止方法 return; } } //遍历完所有元素都没找到匹配项,才抛出异常 throw new DataNotFoundException("不存在该名称的卡种"); }
额外优化建议
可以用Java Stream简化遍历逻辑,代码更简洁:
public void getCards(String cardType) throws DataNotFoundException { boolean exists = getAllAvailableCardType().stream() .anyMatch(card -> cardType.equalsIgnoreCase(card.getCardTypeName())); if (exists) { log.info("恭喜,存在输入名称对应的卡种 "+cardType); } else { throw new DataNotFoundException("不存在该名称的卡种"); } }
内容的提问来源于stack exchange,提问作者Ukeme Elijah
相关产品推荐
相关产品推荐

