首页 > 解决方案 > try and catch 语句没有给我任何结果?

问题描述

**代码的目的是从文件中读取一些数据。数据被分成几行,每行的数据用“-”字符分开。代码应该将数据拆分为单独的字符串,并将单独的字符串传输到一个名为“splitLine”的数组中。测试数据的重点是它会抛出一个“ArrayIndexOutOfBoundsException”。但是,在给出这个异常之后,catch 应该只是允许代码继续,但它不起作用。**

public class asd 

{

    public static void main(String[] args)
    {
        String line = "";
        String[] splitLine;
        Scanner keyboard = new Scanner (System.in);
        System.out.print("Enter the file name: ");
        String filename = keyboard.nextLine();

        Scanner fileReader = null;

        try
        {
            File Fileobject = new File (filename);
            fileReader = new Scanner (Fileobject);
            System.out.println("The file " + filename + " contains the following lines");
            System.out.println("==============================");
            int x=0;




            while(fileReader.hasNext())
            { 
                try 
                {
                    line = fileReader.nextLine();
                    splitLine = line.split(" - "); //For assignment use line.split(" - ")
                    System.out.printf("Title: %20s \nAuthor: %17s \nPublisher: %9s\nPrice: %10s\nPages: %8s\nISBN: %16s\n===================\n", splitLine[x] , splitLine[x+1], splitLine[x+2], splitLine[x+3], splitLine[x+4], splitLine[x+5]);
                } 
                catch (ArrayIndexOutOfBoundsException  e) 
                {
                    continue;
                }





        }
    }
        catch(FileNotFoundException e)
            {
                System.out.println("Error - file does not exist");
                System.exit(0);
            } 

    }
}

标签: javaexceptiontry-catch

解决方案


我建议在访问之前对输入进行验证,而不仅仅是使用它并在异常时失败。


另一个方向:

无论如何-根据您的消息,您的数据是用“-”组织的,那么为什么不将相同的数据保存为 JSON 文件呢?

然后你可以像这样将它读入你的对象:首先,创建你自己的Article.java类然后,编写如下代码:

import com.fasterxml.jackson.*

    public static void someMethod()
    {
        File file = new File("....somepath...\\Desktop\\data.json");
        ObjectMapper mapper = new ObjectMapper();
        Article article = mapper.readValue(file , Article.class);

        System.out.printf("Title: %20s \nAuthor: %17s \nPublisher: %9s\nPrice: %10s\nPages: %8s\nISBN: %16s\n===================\n", article.getTitle(), article.getPublisher(), article.getPrice(), article.getPages(), article.getSomethingMore1(), article.getSomethingMore2());

    }

推荐阅读