问题在于:酒店销售人员在文本文件中输入销售额。每行包含以下内容,以分号分隔:客户的名称,销售的服务(如晚餐,会议,住宿等),销售金额以及该事件的日期。编写一个读取此类文件的程序,并显示每个服务类别的总金额。如果文件不存在,则显示错误格式不正确。
这就是我所拥有的:
package practice;
import java.io.*;
import java.io.FileNotFoundException;
import java.util.*;
import java.io.PrintWriter;
public class practice1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.println("Please enter input file name: ");
String inputFileName = console.next();
System.out.println("Please enter desired output file name: ");
String outputFileName = console.next();
console.useDelimiter(";");
//Construct Scanner and PrintWriter objects for reading and writing
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
double dinnerTotal = 0;
double conferenceTotal = 0;
double lodgingTotal = 0;
double total = dinnerTotal + conferenceTotal + lodgingTotal;
//Read the input and write the output
while (in.hasNext())
{
String line = in.nextLine();
String[] parts = line.split(";");
if(parts[2].equals("Conference")){
conferenceTotal = conferenceTotal+ Double.parseDouble(parts[3]);
} else if(parts[2].equals("Dinner")){
dinnerTotal += Double.parseDouble(parts[3]);
} else if(parts[2].equals("Lodging")){
lodgingTotal += Double.parseDouble(parts[3]);
}
}
out.printf("Dinner Total:", dinnerTotal);
out.println();
out.printf("Conference Total:", conferenceTotal);
out.println();
out.printf("Lodging Total", lodgingTotal);
out.println();
out.printf("Total", total);
in.close();
out.close();
}
}
该程序创建一个如下所示的新文件: 晚餐总计 会议总计 住宿总数 总
但它并不打印实际总数。如何打印总数?
答案 0 :(得分:2)
double total = dinnerTotal + conferenceTotal + lodgingTotal;
行需要低于while
循环。
答案 1 :(得分:0)
printf
要求转换器正常工作。
你应该改变:
out.printf("Dinner Total:", dinnerTotal);
为:
out.printf("Dinner Total: %f", dinnerTotal);
将打印您想要的值。其他行的工作方式相似。
而且,正如@Atri指出的那样,
double total = dinnerTotal + conferenceTotal + lodgingTotal;
应该在循环之后进行,以便正确计算。
答案 2 :(得分:0)
另外要添加回复:你的数组索引是错误的。 Java数组从0开始,因此您需要将所有值移至-1。
我让代码正在改变: