程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

为什么不显示异常错误

发布于2023-03-25 11:03     阅读(1060)     评论(0)     点赞(28)     收藏(5)


      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); 
      }
}  

当我运行此错误时,“你不能那样做”没有出现,但它被视为无效并要求用户重新输入数字直到有效,我怎样才能显示错误行?


解决方案


您需要抛出异常才能捕获异常:

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();
    }
}

编辑:如评论中所述,for 行不是必需的,因为知道该值是否包含在您的 AccountList 中的算法由 contains 方法处理。



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.javaheidong.com/blog/article/661227/a4fbda9bcf17bfb6924c/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

28 0
收藏该文
已收藏

评论内容:(最多支持255个字符)