![](/img/trans.png)
[英]Scanner Try Catch Statement results in java.util.InputMismatchException
[英]The try and catch statement gives me no results?
**代碼的目的是從文件中讀取一些數據。 數據被分成幾行,每行上的數據使用“-”字符分割。 代碼應該將數據拆分為單獨的字符串,並將單獨的字符串傳輸到名為“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());
}
因此,據我所知,當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]);
此外,我建議將內部嘗試提取為單獨的方法以提高可讀性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.