捕获异常并请求用户重新输入输入

时间:2017-11-06 13:09:48

标签: java exception java.util.scanner

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

    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

3 个答案:

答案 0 :(得分:1)

您的问题是您的操作顺序不好。这是您的订单:

  • 处理文件
  • 文件不存在时发出错误
  • 要求新文件名

我建议采用这种方法:

  • 要求提供文件名
  • 检查文件是否存在
  • 如果不存在,请再次询问
  • 处理文件

简而言之,我的方法是:

  • 阅读一些输入
  • 验证输入。如果做错了一些错误处理
  • 进一步处理输入

回到你的问题:创建一个循环,询问文件名,直到File.exists()返回true。也许还要检查File.isFile()(这样人们就无法输入目录)。

仅在循环后创建扫描仪。它仍然会抛出一个异常(Java不知道你已经确定该文件存在)。但异常处理程序代码不需要请求文件名(因此没有循环)。

答案 1 :(得分:0)

如果您使用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");
}

答案 2 :(得分:-1)

你可以尝试一下while循环:

        boolean again =true;

    while(again){
     FileN = scan.nextLine();

            try
            {
                scan = new Scanner(new File (FileN));
                again=false;
            }
            catch(Exception e)
            {
                System.out.println("Could not find file" + e);
                System.out.println("Please enter a valid file name: ");

            }}
相关问题