【问题标题】:Printing out array data stored from File read打印出从文件读取存储的数组数据
【发布时间】: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


【解决方案1】:

问题在于您的 for 循环将每一行都分配给 outputStr 变量:

for (i = 0; i < pName.length; i++) {  
    outputStr = pName[i] + "," + pPrice[i] + "\n";
}

最后看到你的换行符,我假设你想将所有行连接到那个字符串变量中。所以把代码改成

for (i = 0; i < pName.length; i++) {  
    outputStr += pName[i] + "," + pPrice[i] + "\n";
}

当您将变量初始化为 null 时,这可能会引发 NullPointerException。如果是这种情况,只需使用 "" 进行初始化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多