[java] No Such Element Exception?

So here is my code:

public static void getArmor(String treasure)
    throws FileNotFoundException{
    Random rand=new Random();
    Scanner file=new Scanner(new File ("armor.txt"));
    while(!file.next().equals(treasure)){
        file.next(); //stack trace error here
        }
    int min=file.nextInt();
    int max=file.nextInt();
    int defense=min + (int)(Math.random() * ((max - min) + 1));
    treasure=treasure.replace("_", " ");
    System.out.println(treasure);
    System.out.println("Defense: "+defense);
    System.out.println("=====");
    System.out.println();
    }

public static void getTreasureClass(Monster monGet)
throws FileNotFoundException{
    Random rand = new Random();
    String tc=monGet.getTreasureClass();
    while (tc.startsWith("tc:")){
        Scanner scan=new Scanner(new File ("TreasureClassEx.txt"));
        String eachLine=scan.nextLine();
        while(!tc.equals(scan.next())){
        eachLine=scan.nextLine();
        }
        for (int i=0;i<=rand.nextInt(3);i++){
            tc=scan.next();
        }
    getArmor(tc); //stack trace error here
    }
 }

For some reason I get a No Such Element Exception

    at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at LootGenerator.getArmor(LootGenerator.java:43)
at LootGenerator.getTreasureClass(LootGenerator.java:68)
at LootGenerator.getMonster(LootGenerator.java:127)
at LootGenerator.theGame(LootGenerator.java:19)
at LootGenerator.main(LootGenerator.java:11)

I'm not sure why though. Basically my program is searching through two text files - armor.txt and TreasureClassEx.txt. getTreasureClass receives a treasure class from a monster and searches through the txt until it reaches a base armor item (a string that does not start with tc:.) It then searches getArmor for an armor that matches the name of the base armor it got in treasure class. Any advice would be appreciated! Thanks!

The link to the txt files is here: http://www.cis.upenn.edu/~cis110/hw/hw06/large_data.zip

This question is related to java exception

The answer is


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.


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.


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.


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.