import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class logBook
{
public static void main(String[] args) throws FileNotFoundException
{
File inputFile = new File("C:\\Users\\Nick Tate\\Desktop\\Log.txt");
try{
Scanner in = new Scanner(inputFile);
while(in.hasNextLine())
{
in.useDelimiter(";");
String clientName = in.next();
String serviceCost = in.next();
String serviceSold = in.next();
String serviceDate = in.next();
double cost = Double.parseDouble(serviceCost.trim());
System.out.print(clientName);
System.out.printf("%8.2f", cost);
System.out.print(serviceSold);
System.out.print(serviceDate);
}
in.close();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
}
输出:
- John 25.00 Dinner Aug 12 2013
- Bob 200.00 Conference Sep 11 2013
- Clara 450.00 Lodging Oct 25 2013
- Jamie 900.00 Lodging Oct 28 2013
- Rachel 89.00 Dinner Nov 11 2013
- Richard 1000.00 Conference Dec 17 2013
- Nick 2500.00 Dinner Jan 05 2014
到目前为止,我已成功读取了我文件中的每个项目,并解析了相应的变量。我现在需要总计单独服务类别的费用(即晚餐,会议等)。我该怎么做呢?我想添加if()子句检查每个服务,如
if(serviceSold.equals("Dinner")
{ int sum = 0
dinnerTotal = sum++
}
但是,我如何将相应的价格添加到该类别?任何指导? 我最终需要将这些总数写入另一个名为outputLogBook.text的文件。
答案 0 :(得分:0)
您可以执行以下操作:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;
public class logBook
{
public static void main(String[] args) throws FileNotFoundException
{
File inputFile = new File("C:\\Users\\Nick Tate\\Desktop\\Log.txt");
try
{
Scanner in = new Scanner( inputFile );
Map<String, Double> services = new HashMap<String, Double>();
while( in.hasNextLine() )
{
in.useDelimiter(";");
String clientName = in.next();
String serviceCost = in.next();
String serviceSold = in.next();
String serviceDate = in.next();
Double cost = Double.parseDouble (serviceCost.trim() );
System.out.print(clientName);
System.out.printf("%8.2f", cost);
System.out.print(serviceSold);
System.out.print(serviceDate);
if ( services.containsKey( serviceSold ) )
{
services.put( serviceSold, (Double) services.get( serviceSold ) + cost );
}
else
{
services.put( serviceSold, cost );
}
}
for( Map.Entry<String, Double> entry : services.entrySet() )
{
System.out.println(entry);
}
in.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
}
}