【发布时间】:2021-06-05 17:42:14
【问题描述】:
我正在尝试创建一个类,该类使用单独的方法从文件中读取两组数据并将其存储到 2 个不同的数组中。我不知道是读取方法还是我的输出不正确,但我似乎无法弄清楚如何让它打印出所有数据集。我得到文件的最后一行而不是所有内容。
products.txt 中的示例是
Product1,1100
Product2,1205
Product3,1000
主要方法
String[] pName;
double[] pPrice;
String outputStr = null;
int i = 0;
//String name = null;
// Input number of customers
//initialize arrays with size
pPrice=new double[50];
pName=new String[50];
// read from file, the method is incomplete
try {
readFromFile(pName, pPrice, "products.txt");
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File cannot be read");
e.printStackTrace();
}
for (i = 0; i < pName.length; i++) {
outputStr = pName[i] + "," + pPrice[i] + "\n";
}
// Call method before sorting both arrays
display(outputStr);
阅读方法
public static void readFromFile(String[] pName, double[] pPrice, String fileName) throws FileNotFoundException {
// read data from products
// Create a File instance
File file = new File(fileName);
// Create a Scanner for the file
Scanner sc = new Scanner(file);
// Read data from a file, the data fields are separated by ','
// Change the Scanner default delimiter to ','
sc.useDelimiter(",|\r\n");
// Start reading data from file using while loop
int i = 0;
while (sc.hasNext()) {
String name = sc.next();
String cost = sc.next();
//add the customer data through arrays
pName[i] = name;
pPrice[i] = Double.parseDouble(cost);
i++;
}//end while
// Close the file
【问题讨论】:
-
正确。我得到文件的最后一行而不是所有内容。 products.txt 中的示例是 Product1,1100 Product2,1205 Product3,1000 Product4,1230 Product5,3600 Product6,3200
-
那是因为你调用了方法
display之后for循环已经终止。顺便说一句,您应该edit您的问题并添加详细信息,而不是在评论中添加它们。 -
谢谢@Abra!
标签: java arrays output display