首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IOException环路

IOException环路
EN

Stack Overflow用户
提问于 2012-11-26 11:51:41
回答 1查看 308关注 0票数 1

我需要帮助来弄清楚如何循环我的IOException (在这里,我要求一个文件名,直到输入一个有效的文件名)。我需要一个循环,以某种方式识别输入了一个无效的文件,但不确定如何做到这一点。

代码语言:javascript
复制
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] + " ");
        }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-26 11:57:39

好吧,肯定有人会解释如何通过最佳实践等来改进你的代码,但这是一个非常基本的答案,它本身可能会得到改进(假设你的代码在输入有效的情况下可以工作):

代码语言:javascript
复制
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");
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13558427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档