我有一个名为SalesData.txt的文件,其中包含零售商店每天销售的美元销售额数周.文件中的每一行包含七个数字,即一周的每日销售额.数字用逗号分隔.以下是该文件中的示例:
1245.67,1490.07,1679.87,2371.46,1783.92,1461.99,2059.77
2541.36,2965.88,1965.32,1845.23,7021.11,9652.74,1469.36
2513.45,1963.22,1568.35,1966.35,1893.25,1025.36,1128.36
我已将String转换为Double并尝试计算:
>每周的总销售额
>每周的平均每日销售额
>所有周的总销售额
>平均每周销售额
我的问题是Java如何将第一行检测为第1周,将第二行检测为第2周等.并计算数量.以下是语法:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Q1
{
public static void main (String [] args) throws IOException, NumberFormatException
{
//Open the text file
File file = new File("SalesData.txt");
Scanner inputFile = new Scanner (file);
//Read the text file
while (inputFile.hasNext())
{
String weekly_Sale = inputFile.nextLine();
String value = weekly_Sale;
//Split the text by ","
StringTokenizer strtk = new StringTokenizer(value, ",");
//Define array list
ArrayList numList = new ArrayList ();
while (strtk.hasMoreTokens ())
{
numList.add(strtk.nextToken());
}
//Change the data type from String to Double
for (String item:numList)
{
Double result = Double.parseDouble(item);
//System.out.println(result);
}
weekly(result);
}
//Close the text file
inputFile.close();
}
// not sure how to detect the week number
public static void weekly(String numList)
{
for (int i=0; i
{
System.out.println(numList.get(i));
}
}
}
解决方法:
它听起来像一个列表列表,其中内部列表表示特定周的销售额,外部列表表示所有周:
List> saleWeeks;
解析文件时,每行代表一周,因此添加一个新列表:
List salesForTheWeek = new ArrayList<>();
saleWeeks.add(salesForTheWeek);
// parse the line of the file and add the values to salesForTheWeek
后来,每周都与索引有关:
List week1Sales = saleWeeks.get(0);
然后你可以迭代(或流)来添加,平均等.
标签:java,arraylist
来源: https://codeday.me/bug/20190701/1348496.html