0

I am using this code, and for some reason, I'm getting a No Such Element Exception...

numCompanies is being imported from the keyboard and is showing up right and portfolio is an array with [numCompanies][4].

Can anyone figure out why?

for(int i = 0; i < numCompanies; i++)
{
    System.out.print("Stock #" + (i+1) + ": ");
    String stockData = kbReader.nextLine();
    System.out.print("\n\n hi" + stockData);
    Scanner stockLine = new Scanner(stockData);
    for(int j = 0; j < 4; j++)
    {
        portfolio[i][j] = stockLine.next();
    }
}
Tdag
  • 23
  • 3

2 Answers2

1

I have not tested this but probably stockLine.next(); is called even though there is no element left. So maybe this could help:

for(int j = 0; j < 4; j++)
{
    if( stockLine.hasNext() ) {
        portfolio[i][j] = stockLine.next();
    }
    else
    {
        portfolio[i][j] = 0; // or whatever you want it to be by default
    }
}

This will solve the error message but not the fault.

jnodorp
  • 217
  • 2
  • 10
0

You're passing a single string to a Scanner object, but I would say there's a better way of doing this.

If you want to simply read in the input for each value in the string, separated by spaces, then use split():

String stockData = kbReader.nextLine();
String[] data = stockData.split(" ");
if (data.length != 4) {
    System.err.println("Bad data value found!");
} else {
    //run your loop
}
Rogue
  • 11,105
  • 5
  • 45
  • 71