【发布时间】:2016-02-04 04:20:49
【问题描述】:
我需要你的帮助!我有一个班级作业,我必须从 Excel 列表中获取销售数据,将其导入 java,然后输出一个新列表,该列表对产品 ID 和每种产品的销售单位数量进行了排序。这意味着如果原始列表有 5x 产品 ID“1003”,则最终列表应仅列出 1x 产品 ID“1003”,并将 5 个不同的单位销售额合并为一个总数。
编辑:我可能应该显示原始 excel 列表的样子:
ProductID......单位
10004............. 4
10002...................... 2
10004 .... 3
10008 .... 6
10009 .............3
等等等等。所以基本上只需将重复的 ID 组合起来,然后将它们的总销量相加。
我现在被困在两件事上。我正在尝试为最终列表创建一个新的多维数组,但我无法添加唯一的 productID。我尝试使用 for 循环执行此操作,但它仍会添加多个 productID。
另外,我尝试按 Product ID 列按升序对最终数组进行排序,但无法正常工作。
我已将 cmets 与 CAPS LOCK 一起显示这两个问题在哪里!
谢谢大家!!!
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Project1{
public static void main(String[] args) {
Project1 obj = new Project1();
obj.run();
}
public void run() {
String csvFile = "C:/Users/Jenny/Documents/Classwork/SalesData.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
int counter = 0;
int salesDataArrayCounter = 0;
int [][] finalSalesData = new int[200][2];
System.out.println("Product ID\tUnits"); //Headers for original Data
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] salesData = line.split(cvsSplitBy);
while (counter>0) //this allows me to skip first line of data (It's just text, I need the numbers)
{
System.out.println(salesData[0] + " \t\t " + salesData[1]);
int productID = Integer.parseInt(salesData[0]);
int units = Integer.parseInt(salesData[1]);
search: //THIS IS WHERE MY FIRST TROUBLE LIES
{
for (int i = 0; i < finalSalesData.length; i++)
{
if(finalSalesData[i][0]==(productID)) //Should let me find duplicate product ID's and only add the Units to a pre-existing index
{
finalSalesData[i][1] = finalSalesData[i][1] + units;
break search;
}
else //If productID is unique, add new product ID and units to a new slot in the new array
{
finalSalesData[salesDataArrayCounter][0] = productID;
finalSalesData[salesDataArrayCounter][1] = units;
salesDataArrayCounter++;
break search;
}
}
}
break;
}
counter++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("\n\nSorted Sales Data");
System.out.println("\nProductID\tUnits");
//HOW DO I SORT THIS DATA IN ASCENDING ORDER OF PRODUCT IDS?
for (int q = 0; q < finalSalesData.length; q++)
{
for (int j = 0; j < finalSalesData[q].length; j++)
{
System.out.print(finalSalesData[q][j] +"\t\t");
}
System.out.println("");
}
System.out.println("Done");
}
}
【问题讨论】:
-
您可以使用已排序的
Map对键进行排序,然后将其所有订单的总和作为值。 2 只鸟 - 1 块石头。如果你的任务可以接受的话。