NoSuchElementException with Java.Util.Scanner

前端 未结 7 592
感动是毒
感动是毒 2020-11-22 14:38

I am very new to Java but am working through the book Java: How to program (9th ed.) and have reached an example where for the life of me I cannot figure out what the proble

相关标签:
7条回答
  • 2020-11-22 14:57

    NoSuchElementException will be thrown if no more tokens are available. This is caused by invoking nextInt() without checking if there's any integer available. To prevent it from happening, you may consider using hasNextInt() to check if any more tokens are available.

    0 讨论(0)
  • 2020-11-22 14:57

    You must add input.close() at the end...

    0 讨论(0)
  • 2020-11-22 14:59

    NoSuchElementException Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

    http://docs.oracle.com/javase/7/docs/api/java/util/NoSuchElementException.html

    How about this :

    if(input.hasNextInt() )
         number1 = input.nextInt(); // if there is another number  
    else 
         number1 = 0; // nothing added in the input 
    
    0 讨论(0)
  • 2020-11-22 15:02

    You should use hasNextInt() before assigning value to variable.

    0 讨论(0)
  • 2020-11-22 15:08

    Integer#nextInt throws NoSuchElementException - if input is exhausted

    You should check if there is a next line with Integer#hasNextLine

    if(sc.hasNextLine()){
        number1=sc.nextInt();
    }
    
    0 讨论(0)
  • 2020-11-22 15:08

    This error is mostly occur in case of 0nline IDE's on which you are testing your code. It is not configured properly, as if you run the same code on any other IDE/Notepad it works properly because the online IDE is not designed such a way that it will adjust the input code of your format, So you have to take input as the Online IDE supports.

    0 讨论(0)
提交回复
热议问题