gpt4 book ai didi

java - try and catch 语句没有给我结果?

转载 作者:行者123 更新时间:2023-12-01 19:40:47 24 4
gpt4 key购买 nike

**代码的目的是从文件中读取一些数据。数据被分割成几行,每行上的数据使用“-”字符分割。该代码应将数据拆分为单独的字符串,并将单独的字符串传输到名为“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);
}

}
}

最佳答案

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

<小时/>

另一个方向:

无论如何 - 根据您的消息,您的数据是用“-”组织的,那么为什么不将相同的数据保存为 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());

}

关于java - try and catch 语句没有给我结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59176495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com