-2

So I can't seem to figure out the error that the program keeps throwing. it only happens when I select option 2 from my menu and the line of code it directs me to for the error is line 140 which is "userChoice = one.nextInt();"

Any ideas on what could be the problem? This is the error code

java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at TickerReader.main(TickerReader.java:140)

I posted the code on pastebin since it's a longish piece of code https://pastebin.com/dqXQhJvN

4 Answers4

1

It's because there are no more ints to read. You should check hasNextInt() first before calling nextInt().

Steve Smith
  • 2,244
  • 2
  • 18
  • 22
  • use the hasNext() function. if(scan.hasNext()) {// read the input } – victor Apr 04 '17 at 13:21
  • If you do that, you need to manually check that the next input was an integer. (I think you wrote that just as I editted my answer). – Steve Smith Apr 04 '17 at 13:22
  • Can the upvoter please learn to read the question? This is obivously not the solution to the problem, just a way to handle a symptom. – Tom Apr 04 '17 at 13:24
  • What's wrong with checking `hasNextInt()`? Unless, by "solution" you mean writing the full working program for OP? – Steve Smith Apr 04 '17 at 13:33
  • No, by "solution" I mean to actually fix the issue. But this is not necessary anyway, because this question is a duplicate. – Tom Apr 04 '17 at 14:01
0

When using Scanner's nextInt(), it's always best to check first if it hasNextInt() first.

Ishnark
  • 661
  • 6
  • 14
0

You should check to see if there are more ints to be read hasNextInt() should do it, you could also change your if/else statements for a switch(userChoice ) statement

Julito Sanchis
  • 1,406
  • 2
  • 10
  • 10
0

I was able to resolve the error by taking

Scanner two = new Scanner(System.in); two.close(); And putting them before the if, else if statement.