**该代码的目的是从文件中读取一些数据。数据分为几行,每行的数据都使用“-”字符进行拆分。该代码应将数据拆分为单独的字符串,并将单独的字符串传输到称为“ 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);
}
}
}
答案 0 :(得分: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());
}
答案 1 :(得分:0)
据我所知,当splitLine
不包含必需值时,您想跳过迭代吗?
在那种情况下,仅仅检查您是否有足够的参数会不会更简单?
splitLine = line.split(" - "); //For assignment use line.split(" - ")
if(splitLine.lenght != 6) {
continue;
}
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]);
此外,我建议将内部try提取为单独的方法,以提高可读性