Question

I'm reading in a transaction file that looks like this:

1112, D
4444, A, Smith, Jones, 45000, 2, Shipping
6666, U, Jones
8900, A, Hill, Bill, 65000, 0, Accounting

When I attempt to read the file line by line using ", " the token, the program bombs out with a NoSuchElementException error at the first record. I've deduced that the condition in which I'm reading the file is causing the issue, particularly at the while loop below. I've tried using an "if" statement and setting the conditions to "while (st2.hasMoreTokens)" and a combination of the two but the error persists and I'm not sure why? Thank you in advance for any assistance. This is the code below:

Scanner transactionFile = new Scanner (new File(fileName2));

        for (int i = 0; i < T_SIZE; i++) {
            line2[i] = transactionFile.nextLine();

            transaction[i] = new Transaction();

            st2 = new StringTokenizer(line2[i], ", ");

            transaction[i].setEmployeeID(Integer.parseInt(st2.nextToken()));
            transaction[i].setAction(st2.nextToken());

            while ((transaction[i].getAction() != "D")) {
                transaction[i].setLastName(st2.nextToken());
                transaction[i].setFirstName(st2.nextToken());
                transaction[i].setSalary(Integer.parseInt(st2.nextToken()));
                transaction[i].setNumOfDependants(Integer.parseInt(st2.nextToken()));
                transaction[i].setDepartment(st2.nextToken());
            }
        }
Was it helpful?

Solution

Take a look at the your while loop. The == operator in Java checks if two objects are the same reference, which is rarely a good idea to rely on, and probably causes this loop to loop infinately (or at least until the program crashes with an exception). What you'd want to do, logically, is check that both strings are equal, i.e., both contain the string "D":

while (!transaction[i].getAction().equals("D"))

OTHER TIPS

str.nextToken() 

function access an element when it is called and increments index of it so your are calling it more then the elements in array so it cant have the access to the higher indexes and throws an exception of noSuchElementFound

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top