簡體   English   中英

打印出從文件讀取存儲的數組數據

[英]Printing out array data stored from File read

我正在嘗試創建一個 class,它使用單獨的方法從文件中讀取兩組數據並將其存儲到 2 個不同的 arrays 中。 我不知道是讀取方法還是我的 output 不正確,但我似乎無法弄清楚如何讓它打印出所有數據集。 我得到文件的最后一行而不是所有內容。

products.txt 中的示例是

產品1,1100

產品2,1205

產品3,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

問題是您的 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。 如果是這種情況,只需使用“”進行初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM