Shan Solo
Shan Solo

Reputation: 57

for loops and if statement error occuring

I can't figure out why I get the error:

java.util.NoSuchElementException null(in java.util.Scanner)

in my method:

public void processTransactions(Scanner transFile){

        while (transFile.hasNext()){
           for(i = 0; i < ids.length; i++){
               finalInventory[i] = startingInventory[i];

               if(ids[i] == transFile.next()){
                   finalInventory[i] += transFile.nextInt();
                }
            }
        }
    }

this is my construtor:

public SoftDrinkInventory(Scanner inventoryFile) {

        initializeString(names);
        initializeString(ids);
        initializeInt(startingInventory);
        initializeInt(finalInventory);
        initializeInt(transactionCounts);

        while (inventoryFile.hasNext()){
            names[i] = inventoryFile.next();
            ids[i] = inventoryFile.next();
            startingInventory[i] = inventoryFile.nextInt();
            i++;
        }
    }

All variables have been declared previously in the class.

Upvotes: 0

Views: 83

Answers (2)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79875

I'm guessing a little, but I think your code was supposed to be this.

public void processTransactions(Scanner transFile){

    while (transFile.hasNext()){
       String key = transFile.next();
       int value = transFile.nextInt();
       for(i = 0; i < ids.length; i++){
           finalInventory[i] = startingInventory[i];

           if(ids[i].equals(key)){
               finalInventory[i] += value;
            }
        }
    }
}

You only want to do the next() and the nextInt() once per iteration of the while loop. Currently, you are repeating the next() in every iteration of the for loop, which really isn't what you want.

Note that this isn't the most efficient solution to your problem, but it will take away your error.

Also, you haven't specified the type of ids, but I've assumed that it's a String[].

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201537

You are calling hasNext() but using nextInt() ... One solution is to use,

 while (transFile.hasNextInt()){
   // As before.
 }

Another is to skip anything that isn't an int, perhaps like so

while (transFile.hasNext()){
  if (!transFile.hasNextInt()) {
    transFile.next();
    continue;
  }
  // As before.
}

Upvotes: 1

Related Questions