No Such Element Exception?

后端 未结 5 1503
南旧
南旧 2020-12-01 23:33

So here is my code:

public static void getArmor(String treasure)
    throws FileNotFoundException{
    Random rand=new Random();
    Scanner file=new Scanner         


        
相关标签:
5条回答
  • 2020-12-02 00:19

    I Know this question was aked 3 years ago, but I just had the same problem, and what solved it was instead of putting:

     while (i.hasNext()) {
        // code goes here 
    }
    

    I did one iteration at the start, and then checked for condition using:

    do {
       // code goes here
    } while (i.hasNext());
    

    I hope this will help some people at some stage.

    0 讨论(0)
  • 2020-12-02 00:27

    It looks like you are calling next even if the scanner no longer has a next element to provide... throwing the exception.

    while(!file.next().equals(treasure)){
            file.next();
            }
    

    Should be something like

    boolean foundTreasure = false;
    
    while(file.hasNext()){
         if(file.next().equals(treasure)){
              foundTreasure = true;
              break; // found treasure, if you need to use it, assign to variable beforehand
         }
    }
        // out here, either we never found treasure at all, or the last element we looked as was treasure... act accordingly
    
    0 讨论(0)
  • 2020-12-02 00:27

    Looks like your file.next() line in the while loop is throwing the NoSuchElementException since the scanner reached the end of file. Read the next() java API here

    Also you should not call next() in the loop and also in the while condition. In the while condition you should check if next token is available and inside the while loop check if its equal to treasure.

    0 讨论(0)
  • 2020-12-02 00:33

    Another situation which issues the same problem, map.entrySet().iterator().next()

    If there is no element in the Map object, then the above code will return NoSuchElementException. Make sure to call hasNext() first.

    0 讨论(0)
  • 2020-12-02 00:38

    I had run into the same issue while I was dealing with large dataset. One thing I've noticed was the NoSuchElementException is thrown when the Scanner reaches the endOfFile, where it is not going to affect our data.

    Here, I've placed my code in try block and catch block handles the exception. You can also leave it empty, if you don't want to perform any task.

    For the above question, because you are using file.next() both in the condition and in the while loop you can handle the exception as

    while(!file.next().equals(treasure)){
        try{
            file.next(); //stack trace error here
           }catch(NoSuchElementException e) {  }
    }
    

    This worked perfectly for me, if there are any corner cases for my approach, do let me know through comments.

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