我有一个从文本文件中读取信息并以有组织的格式显示的程序。如果文本文档的格式不符合预定格式,如何生成错误。如何在.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