No Such Element Exception?

后端 未结 5 1529
南旧
南旧 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: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.

提交回复
热议问题