Question

So I have some code that is supposed to use a jfilechooser get a text file use a split and scanner with a colon as a delimeter and store the data into an array. The code and text is as seen below. I have added a segment of code to test if the array length is less than 1 and it always is even though I have set it to to store in a String array. Why is it doing this and how can I get it to store the text from each line of the code into an array of 6 intervals?

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);

        }

    }
}

John:Smith:Manufacturing:6.75:120:444

Betty:White:Manager:1200.00:111

Stan:Slimy:Sales:10000.00:332

Betty:Boop:Design:12.50:50:244

Was it helpful?

Solution

Your Scanner is taking in a String instead of the variable. Instead of

Scanner scan = new Scanner("empFile");

Try

Scanner scan = new Scanner(empFile);

From the docs

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

You're currently scanning the string "empFile" instead of the actual file currently.

OTHER TIPS

The problem comes beacuse you try to use the scanner before there is any chosen file:

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

Instead you need to change your code so that you create the scanner only after the file is selected

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

    Scanner scan = new Scanner("empFile");
    while(scan.hasNext()){
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top