No Such Element Exception?

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

提交回复
热议问题