簡體   English   中英

字符串數組不存儲文本文件中的數據

[英]String array not storing data from text file

因此,我有一些應該使用jfilechooser的代碼來獲取文本文件,並使用分號和掃描儀(以冒號作為定界符)並將數據存儲到數組中。 代碼和文本如下所示。 我添加了一段代碼來測試數組長度是否小於1,即使我將其設置為存儲在String數組中,它也總是如此。 為什么這樣做,如何將代碼每一行中的文本存儲到6個間隔的數組中?

else if (e.getSource()==readButton) {
    JFileChooser fileChooser = new JFileChooser("Local Disk (C:)");
    if  (fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
    {
        empFile=fileChooser.getSelectedFile();
    }
    Scanner scan = new Scanner("empFile");
    while(scan.hasNext()) {
        String[] rowData = scan.nextLine().split(":");
        if (rowData.length < 1){
            System.out.println("error");
        }
        else if(rowData.length == 5) {
            rowData[4] = "0";
            fName = rowData[0];
            lName = rowData[1];
            position2 = rowData[2];
            firstParam = Double.parseDouble(rowData[3]);
            empNum = Integer.parseInt(rowData[4]);

            c.addEmployee(fName, lName, position2, firstParam, 0, empNum);

        }
        else {
            fName = rowData[0];
            lName = rowData[1];
            position2 = rowData[2];
            firstParam = Double.parseDouble(rowData[3]);
            secondParam = Integer.parseInt(rowData[4]);
            empNum = Integer.parseInt(rowData[5]);

            c.addEmployee(fName, lName, position2, firstParam, secondParam, empNum);

        }

    }
}

約翰:史密斯:制造:6.75:120:444

貝蒂:白:經理:1200.00:111

Stan:Slimy:Sales:10000.00:332

貝蒂:大桶:設計:12.50:50:244

您的掃描儀將使用字符串而不是變量。 代替

Scanner scan = new Scanner("empFile");

嘗試

Scanner scan = new Scanner(empFile);

來自文檔

 Scanner(String source) Constructs a new Scanner that produces values scanned from the specified string. 

您當前正在掃描字符串“ empFile”,而不是當前的實際文件。

之所以出現此問題,是因為您在選擇任何文件之前嘗試使用掃描儀:

 if  (fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
 {
    empFile=fileChooser.getSelectedFile();
 }
 Scanner scan = new Scanner("empFile");
 while(scan.hasNext()){
 }

相反,您需要更改代碼,以便僅在選擇文件后才創建掃描儀

 if  (fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
 {
    empFile=fileChooser.getSelectedFile();

    Scanner scan = new Scanner("empFile");
    while(scan.hasNext()){
    }
}

暫無
暫無

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

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