java - 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);
}
}
}
解决方案
我建议在访问之前对输入进行验证,而不仅仅是使用它并在异常时失败。
另一个方向:
无论如何-根据您的消息,您的数据是用“-”组织的,那么为什么不将相同的数据保存为 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());
}
推荐阅读
- spring - 如何在百里香春季电子邮件模板中添加自定义字体?
- json - 对 JSON 消息进行编码,使其适合 Microsoft Power Automate 中的 JSON 值
- java - 添加水印限制
- android - 如何在可访问性本地上下文菜单中添加自定义操作
- python-2.7 - 在 Ubuntu 18.04 上运行 pip install ipdb 时出现“导入错误:没有名为 msvc 的模块”
- rust - 是否有一个内在的原因可以解释为什么 Rust 没有更高种类的类型?
- go - 如何计算复杂映射变量的内存大小
- python - 如何找到数据的集体异常?
- mysql - 在 MariaDB 中以两个不同的名称访问表
- android - 如何从我的 PC 安装 android 应用程序手机?