类对象未显示导入文件中的正确信息;找不到数据丢失的位置



除了导入的数据外,一切正常;数字根本没有被读取(除了0(。问题可能出在 BufferedReader(我不经常使用的东西(上,也可能是我的数组列表组织错误。没有错误,所以我不确定数据丢失的位置。

显示信息的类:

import java.io.*;
import java.util.*;
import javax.swing.*;
import java.text.*;    
public class Sales
{
public static void main(String[] args) throws IOException
{
final int ONE_WEEK = 7;
double[] sales = new double[ONE_WEEK];
SalesData week = new SalesData(sales);
DecimalFormat dollar = new DecimalFormat("#,##0.00");
JOptionPane.showMessageDialog(null,
"The total sales were $" +
dollar.format(week.getTotal()) +
"nThe average sales were $" +
dollar.format(week.getAverage()) +
"nThe highest sales were $" +
dollar.format(week.getHighest()) +
"nThe lowest sales were $" +
dollar.format(week.getLowest()));
System.exit(0);
}
}

收集和组织信息的类:

import java.io.*;
import java.util.*;
public class SalesData{
private double[] sales;
public SalesData(double[] s) throws IOException{
sales = new double[s.length];
for (int index = 0; index < s.length; index++){
sales[index] = s[index];
}
File f = new File("SalesData.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String str = input.readLine();
String[] stringSales = str.split(",");
Double[] doubleSales = new Double[str.length()];
for (int i=0; i<stringSales.length;i++){
doubleSales[i] = Double.parseDouble(stringSales[i]);
}
}
public double getTotal(){
double total = 0.0;
for (int index = 0; index < sales.length; index++){
total += sales[index];
}
return total;
}
public double getAverage(){
return getTotal() / sales.length;
}
public double getHighest(){
double highest = sales[0];
for (int index = 1; index < sales.length; index++){
if (sales[index] > highest)
highest = sales[index];
}
return highest;
}
public double getLowest(){
double lowest = sales[0];
for (int index = 1; index < sales.length; index++){
if (sales[index] < lowest)
lowest = sales[index];
}
return lowest;
}
}

从以下位置收集信息的文件:

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[] stringSales = str.split(",");
Double[] doubleSales = new Double[str.length()];// this will be 55 ish instead of 7

你想要Double[] doubleSales = new Double[stringSales.length()];

for (int i=0; i<stringSales.length;i++){
doubleSales[i] = Double.parseDouble(stringSales[i]);           
}

你想在这里填充销售数组,而不是像这样填充 doubleSale[]:

sales[i] = Double.parseDouble(stringSales[i]);

只需确保您的输入文件每行只有 7 个值,以避免 ArrayIndexOutOfBound 错误。

最新更新