栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

异常处理,捕获引起while循环停止的原因

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

异常处理,捕获引起while循环停止的原因

try / catch块需要在循环内部。

当引发异常时,控制会尽可能地爆发,直到遇到遇到catch块的情况为止(在您的情况下,该catch块在循环之外)。

public static void readNumbers(){    File inputFile = new File ("C:/users/AC/Desktop/input.txt");    try {        Scanner reader = new Scanner(inputFile);        while(reader.hasNext())        { try {     int num = reader.nextInt();     System.out.println("Number read: " +num); } catch (InputMismatchException e) {     System.out.println("Input error "); }        }    }    catch (FileNotFoundException e2)    {        System.out.println("File not found!");      }}

我尝试将所有内容放入while循环中,并且由于输入异常而无休止地循环。

您提到您已经尝试过了。我需要您遇到的问题的更多详细信息,因为这是正确的方法。我的头顶上只是一个预感,也许是当发生异常时reader.nextInt()不会提高读者在文件中的位置,因此再次调用nextInt会读取相同的非整数块。

也许您的catch块需要调用reader.getSomethingElse?像reader.next()一样?

这是一个主意,我还没有测试过:

public static void readNumbers(){    File inputFile = new File ("C:/users/AC/Desktop/input.txt");    try {        Scanner reader = new Scanner(inputFile);        while(reader.hasNext())        { try {     int num = reader.nextInt();     System.out.println("Number read: " +num); } catch (InputMismatchException e) {     System.out.println("Input error ");     reader.next();   // THIS LINE IS NEW }        }    }    catch (FileNotFoundException e2)    {        System.out.println("File not found!");      }}

[编辑9:32 PM]

我对提升读者是正确的。

根据扫描仪的Java文档:

将输入的下一个标记扫描为int。如果下一个标记不能转换为有效的int值,则此方法将引发InputMismatchException,如下所述。
如果翻译成功,则扫描程序将前进经过匹配的输入。

http://docs.oracle.com/javase/7/docs/api/



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/506189.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号