公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(50元/站),

点击这里在线咨询客服
新站提交
  • 网站:51998
  • 待审:31
  • 小程序:12
  • 文章:1030137
  • 会员:747

本文介绍了捕获异常并请求用户重新输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个打开然后读取用户指定的文件的程序,目前我拥有的代码如下所示:

    System.out.println("Enter the name of the file you want to open: ");
    FileN = scan.nextLine();
    // I want the program to return to this point here if an error has occured.
    try
    {
        scan = new Scanner(new File (FileN));
    }
    catch(Exception e)
    {
        System.out.println("Could not find file" + e);
        System.out.println("Please enter a valid file name: ");

    }

我已经在上面指定了我希望程序在代码中返回的位置,我目前已经尝试创建一个循环,然后使用Continue,但是它不会让我在循环中尝试。此外,我试图创造一个新的空白,但它仍然不起作用。当前,即使用户输入了无效的文件名,程序也会继续运行。

我已经搜索了答案,但只能找到与我想要的内容相关的答案:Java – Exception handling – How to re-enter invalid input

还澄清了在循环中尝试是什么意思;是的,这是可能的。但是,我想知道为了继续在我的程序中工作,我是将try放入循环中,还是将循环放入try中?我已经提到:Should try…catch go inside or outside a loop?

This is the error I’m currently getting with my latest code

推荐答案

如果您使用Exception,从它的本意是用来处理意想不到的事情的意义上来说,它会变得更容易一些。正如预期的那样,不存在的文件并不是真正的例外。存在但无法打开的文件,或者正在打开但内容为零的文件(即使它有1MB的内容)是意想不到的事情,因此也是例外。考虑到不存在的文件的预期行为(因为它是由用户键入的,而用户可能键入不正确),您可以使用如下内容:

boolean fileExists = false;
File newFile;
while(!fileExists) {
  System.out.println("Enter the name of the file you want to open: ");
  FileN = scan.nextLine();
  newFile = new File(FileN);
  fileExists = newFile.exists();
  if (!fileExists) {
    System.out.println(FileN + " not found...");
  }
}
try {
    Scanner scan;
    scan = new Scanner(newFile);
    ... do stuff with the scanner
}
catch(FileNotFoundException fnfe) {
  System.out.println("sorry but the file doesn't seem to exist");
}

这篇关于捕获异常并请求用户重新输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,

分享到:
标签:异常 捕获 用户 请求 重新输入
用户无头像

网友整理

注册时间:

网站:5 个   小程序:0 个  文章:12 篇

  • 51998

    网站

  • 12

    小程序

  • 1030137

    文章

  • 747

    会员

赶快注册账号,推广您的网站吧!
最新入驻小程序

数独大挑战2018-06-03

数独一种数学游戏,玩家需要根据9

答题星2018-06-03

您可以通过答题星轻松地创建试卷

全阶人生考试2018-06-03

各种考试题,题库,初中,高中,大学四六

运动步数有氧达人2018-06-03

记录运动步数,积累氧气值。还可偷

每日养生app2018-06-03

每日养生,天天健康

体育训练成绩评定2018-06-03

通用课目体育训练成绩评定