gpt4 book ai didi

java - 从java中的csv列添加: how do I reset variable total?

转载 作者:行者123 更新时间:2023-12-01 19:33:53 25 4
gpt4 key购买 nike

正如标题所示,我正在尝试获取 3 个单独的总计(每个 empID 一个)和一个 grandTotal;

import java.util.*;
import java.io.*;
public class SalesReport{

public static void main(String[] args)throws IOException{
File f = new File("sales.csv");
Scanner in = new Scanner(f);
int empID = 0;
double sales = 0.0;
double total = 0.0;
double allTotal = 0.0;
System.out.println("Brewster's Used Cars, Inc.\nSales Report\n\nSalesperson ID\t\tSales Amount");
for(int i = 0;i<43;i++){
System.out.print("≡");
}
System.out.print("\n");
while(in.hasNext()){
String data = in.next();
String[] field = data.split(",");
sales = Double.parseDouble(field[1]);
if(empID == 0){
empID = Integer.parseInt(field[0]);
}
if(Integer.parseInt(field[0])!=empID){
System.out.printf("Total sales for this salesperson: $%,3.2f\n", total);
empID = Integer.parseInt(field[0]);
total += sales;
}
else{
total += sales;
}
System.out.printf(empID + "\t\t\t$%,3.2f\n", sales);
}
allTotal += total;
System.out.printf("Total sales for this salesperson: $%,3.2f\n", total);
System.out.printf("Total of all sales: $%,3.2f\n", allTotal);
in.close();
}
}

此输出:

Brewster's Used Cars, Inc.
Sales Report

Salesperson ID Sales Amount
≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡
100 $10,000.00
100 $12,000.00
100 $5,000.00
Total sales for this salesperson: $27,000.00
101 $14,000.00
101 $18,000.00
101 $12,500.00
Total sales for this salesperson: $71,500.00
102 $13,500.00
102 $14,500.00
102 $20,000.00
Total sales for this salesperson: $119,500.00
Total of all sales: $119,500.00.

我尝试将 total = 0.0; 添加到第二个 if 语句,将前 2 个总计变为 0,尽管第三个是正确的。所以问题是,我如何获得这一大堆代码来计算个人的总数和销售总额?

最佳答案

在第二个 if(读取 if(Integer.parseInt(field[0])!=empID))中,尝试设置 total = sales 而不是 总计 += 销售额 就像现在一样。

在 Java 中,使用 = 为变量赋值,使用 += 为现有变量添加附加值。

关于java - 从java中的csv列添加: how do I reset variable total?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59238707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com