这是我从文件中读取并显示在控制台中的代码
try
{
BufferedReader readFile = new BufferedReader(new FileReader("sales.txt"));
String line = "";
while((line = readFile.readLine()) != null)
{
String tmp[] = line.split(",");
year = Integer.parseInt(tmp[0]);
quarter = tmp[1];
sales = Integer.parseInt(tmp[2]);
//System.out.printf("Year: %stQuarter: %stSales: %dn",year,quarter,sales);
}
readFile.close();
}
catch(IOException e)
{
e.printStackTrace();
}
userInput.close();
在我名为"sales.txt"的文件中,我有这个:
2012年第1,9300季度
2012年第2季度,10225
2012,第三季度,12420
2012年第4季度,13250
2013年第1季度,10500
2013年第2季度,10900
2013,第三季度,11340
2013年第4季度,14600
现在我纠结于如何计算 2012 年和 2013 年第 4 季度的平均销售额
仅针对这种情况:
float avg = 0;
int counter = 0;
try
{
BufferedReader readFile = new BufferedReader(new FileReader("sales.txt"));
String line = "";
while((line = readFile.readLine()) != null)
{
String tmp[] = line.split(",");
year = Integer.parseInt(tmp[0]);
quarter = tmp[1];
sales = Integer.parseInt(tmp[2]);
if(year == 2012 || year == 2013)
if(quarter.equals("Q4"){
counter++;
avg+=sales;
}
//System.out.printf("Year: %stQuarter: %stSales: %dn",year,quarter,sales);
}
avg /= counter; //Here there is the average! in avg
readFile.close();
}
catch(IOException e)
{
e.printStackTrace();
}
userInput.close();
//或从文件中读取为数组
int[] year = new int [lineCount];
String[] quarter = new String [lineCount];
int[] sale = new int [lineCount];
Scanner readFile = new Scanner(new File("sales.txt"));
while(readFile.hasNextLine())
{
String salesRecords = readFile.nextLine();
Scanner lineScan = new Scanner(salesRecords);
lineScan.useDelimiter(",");
year[i] = lineScan.nextInt();
quarter[i] = lineScan.next();
sale[i] = lineScan.nextInt();
lineScan.close();
i++;
}
//Read from file and store data in Array List
Scanner inputFile = new Scanner(new File("sales.txt"));
ArrayList<Integer> yearsList = new ArrayList<Integer>();
ArrayList<String> quartersList = new ArrayList<String>();
ArrayList<Integer> salesList = new ArrayList<Integer>();
while(inputFile.hasNextLine()){
String line = inputFile.nextLine();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while(scanner.hasNextLine()){
yearsList.add(scanner.nextInt());
quartersList.add(scanner.next());
salesList.add(scanner.nextInt());
}
scanner.close();
}
inputFile.close();
//. Testing Can I read the file properly
// System.out.println(years+" n" + quarters + " n" + sales);
//. Convert from ArrayList into Array
Integer[]yearsArray = yearsList.toArray(new Integer[yearsList.size()]);
String[] quartersArray = quartersList.toArray(new String[quartersList.size()]);
Integer[]salesArray = salesList.toArray(new Integer[salesList.size()]);