java - IO异常循环

标签 java loops ioexception

我需要帮助弄清楚如何循环我的IOException(在其中我要求输入文件名,直到输入有效的文件名)。我需要一个循环,以某种方式识别输入了无效文件,但不确定如何执行此操作。

import java.util.*;
import java.io.*;
public class JavaGradedLab {
    public static void main(String[] args) throws IOException {

        Scanner inScan, fScan = null;
        int [] A = new int[5];
        inScan = new Scanner(System.in);
        System.out.println("Please enter the file to read from: ");

        try{
            String fName = inScan.nextLine();
            fScan = new Scanner(new File(fName));
        }

        catch (FileNotFoundException ex)
        {
            System.out.println("Your file is invalid -- please re-enter");
        }

        String nextItem;
        int nextInt = 0;
        int i = 0;

        while (fScan.hasNextLine())
        {
            nextItem = fScan.nextLine();
            nextInt = Integer.parseInt(nextItem);
            A[i] = nextInt;
            i++;
        }

        System.out.println("Here are your " + i + " items:");
        for (int j = 0; j < i; j++)
        {
            System.out.println(A[j] + " ");
        }
    }
}

最佳答案

嗯,肯定会有人解释如何通过最佳实践等使您的代码变得更好,但作为一个非常基本的答案,其本身可能可以改进(假设您的代码在输入有效时工作):

while(true) {
    try{
        String fName = inScan.nextLine();
        fScan = new Scanner(new File(fName));
        break;
    }
    catch (FileNotFoundException ex)
    {
        System.out.println("Your file is invalid -- please re-enter");
    }
}

关于java - IO异常循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13558427/

相关文章:

java - JTable 输入键

java - hibernate 状态下的 Postgresql 'select distinct on'

variables - 计算循环中的变量数量

java - 在自定义数组列表中搜索最有效

Java:通过 LAN 网络进行序列化时遇到问题

java - Pair 类 getPair 方法

java - 如何在 Buffer Writer 中创建新行 - Java

javascript - javascript 中 json 的循环问题

Android 蓝牙 .connect() 异常 Nexus 7 OBDII 适配器

java - IOException 冒险