我有一個從文本文件中讀取信息並以有組織的格式顯示的程序。如果文本文檔的格式不符合預定格式,如何生成錯誤。如何在.txt格式不正確時生成錯誤
這是我到目前爲止有:
package question;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class question1{
public static void displayResults(double dinnerExpense, double lodgingExpense, double conferenceExpense)
{
System.out.println("Dinner expense: $"+dinnerExpense);
System.out.println("Lodging expense: $"+lodgingExpense);
System.out.println("Conference expense: $"+conferenceExpense);
}
public static void searchAndDisplayFile(String name)
{
try
{
Scanner inFile = new Scanner(new File(name));
double dinnerExpense=0;
double lodgingExpense=0;
double conferenceExpense=0;
while(inFile.hasNext())
{
inFile.useDelimiter("; ");
String activity =inFile.next();
if (activity.equals("Dinner"))
{
dinnerExpense+=(inFile.nextDouble());
}
if (activity.equals("Lodging"))
{
lodgingExpense+=(inFile.nextDouble());
}
if (activity.equals("Conference"))
{
conferenceExpense+=(inFile.nextDouble());
}
}
inFile.close();
displayResults(dinnerExpense, lodgingExpense,conferenceExpense);
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
}
public static void main(String[] args) throws FileNotFoundException{
Scanner in = new Scanner (System.in);
System.out.println("Please enter the file name: ");
String name = in.nextLine();
searchAndDisplayFile(name);
System.out.println("Make sure the file exists or is type correctly.");
}
}
我該如何去使用這個語法。即如果單詞文檔未格式化爲「名稱;類別;花費的金額」,它會產生錯誤? – kjd82
你可以添加如何格式化文件,以及如何搜索名稱,類別和金額花費? – Arlind
例如「John Doe;晚餐; 146.54; 2014年6月12日」晚餐可以在任何會議或住宿中進行。 – kjd82