Skip to content

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(!{; //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("Defense: "+defense);

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();
        for (int i=0;i<=rand.nextInt(3);i++){
    getArmor(tc); //stack trace error here

For some reason I get a No Such Element Exception

    at java.util.Scanner.throwFor(
at LootGenerator.getArmor(
at LootGenerator.getTreasureClass(
at LootGenerator.getMonster(
at LootGenerator.theGame(
at LootGenerator.main(

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:


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


Should be something like

boolean foundTreasure = false;

          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