-2

I'm working on a Choose Your Adventure game in Java, and I'm really confused why I'm getting a NoSuchElementException when the variable adolescenceIntro is used (see main function). The birth variable and all of the variables it calls work perfectly fine, so I don't know what is happening with adolescenceIntro. As you will see, there are other classes I use within this one, but I don't think they are causing the issue. Please let me know what I am doing wrong!

  //import java.util.HashMap;
import java.util.Scanner;


public class ChooseYourAdventure {


    //private static HashMap<String, Storyline> stories = new HashMap<String, Storyline>();

    private static Storyline death = new Storyline(0, 0, 0, Storylines.deathText, null, null);

    // adolescence
    private static Storyline glue = new Storyline(0, -1, 0, Storylines.glueText, null, null);
    private static Storyline befriendDavid = new Storyline(0, 3, 2, Storylines.befriendDavidText, null, null);
    private static Storyline dinosaurIsland = new Storyline(0, 1, 1, Storylines.dinosaurIslandText, null, null);
    private static Storyline buildCastle = new Storyline(0, 3, 2, Storylines.buildCastleText, null, null);
    private static Storyline terrorize = new Storyline(0, 0, 0, Storylines.terrorizeText, befriendDavid, glue);
    private static Storyline comply = new Storyline(0, 0, 0, Storylines.complyText, buildCastle, dinosaurIsland);
    private static Storyline adolescenceIntro = new Storyline(0, 0, 1, Storylines.adolescenceIntroText, comply, terrorize);

    // infancy
    private static Storyline sleepItOff = new Storyline(0, -2, 0, Storylines.sleepItOffText, null, null);
    private static Storyline cryMore = new Storyline(0, 3, 1, Storylines.cryMoreText, null, null);
    private static Storyline cooperate = new Storyline(0, 5, 0, Storylines.cooperateText, null, null);
    private static Storyline screamLouder = new Storyline(0, 0, 0, Storylines.screamLouderText, death, death);
    private static Storyline moneyIssues = new Storyline(0, -2, 0, Storylines.moneyIssuesText, cryMore, sleepItOff);
    private static Storyline cry = new Storyline(0, -2, 0, Storylines.cryText, cooperate, screamLouder);
    private static Storyline birth = new Storyline(0, 0, 0, Storylines.birthText, moneyIssues, cry);


    public ChooseYourAdventure()
    {

    }

    public static void main(String[] args)
    {
        ChooseYourAdventure cyaGame = new ChooseYourAdventure();
        Character player = new Character();
        System.out.println("\n-----| CHAPTER 1: INFANCY |-----\n");
        cyaGame.playStoryline(birth, player);
        if(player.checkIsDead() == true)
        {
            return;
        }
        System.out.println("\n\n-----| CHAPTER 2: ADOLESCENCE |-----\n");
        player.setAge(4);
        cyaGame.playStoryline(adolescenceIntro, player);
        System.out.println("\n\n-----| CHAPTER 2: YOUNG ADULTHOOD |-----\n");
        System.out.println("\n\n-----| CHAPTER 2: ADULTHOOD |-----\n");
        System.out.println("\n\n-----| CHAPTER 2: OLD AGE |-----\n");

    }

    public void playStoryline(Storyline story, Character p)
    /**
     * display text,stats
     * call nextStoryLine
     */
    {
        p.addHappiness(story.getHappinessChange());
        p.addMeaning(story.getMeaningChange());

        System.out.println("Current age: " + p.getAge());
        System.out.println("\nHappiness level: " + p.getHappiness());
        System.out.println("Meaning level: " + p.getMeaning() + "\n");
        System.out.println(story.getText());
        p.addAge(story.getAgeChange());
        nextStoryline(story, p);
    }

    public void nextStoryline(Storyline story, Character p)
    {   
        if(story.getOption1() == null) // end of chapter
        {
            return;
        }

        else if(story.getOption1().equals(death)) // end of game
        {
            p.setIsDead(true);
            System.out.println(death.getText());
            return;
        }
        else
        {
            System.out.println("\nSelect your option by typing \"1\" or \"2.\"");
            Scanner scr = new Scanner(System.in);
            String answer = scr.nextLine();
            if(answer.equals("1"))
            {
                System.out.println("\n-------\n");
                playStoryline(story.getOption1(), p);
            }
            else if(answer.equals("2"))
            {
                System.out.println("\n-------\n");
                playStoryline(story.getOption2(), p);
            }
            else
            {
                System.out.println("Invalid input; please try again");
                System.out.println("\n-------\n");
                nextStoryline(story, p);
            }
            scr.close();
        }
    }

//  public static void printStoriesInfo()
//  {
//      System.out.println("number of stories: " + Storyline.numberOfStories);
//      System.out.println("\n-------\n");
//      System.out.println("entry set: " + stories.entrySet());
//      System.out.println("\n-------\n");
//      System.out.println("keys: stories.keySet() = " + stories.keySet());
//      System.out.println("\n-------\n");
//      System.out.println("text:");
//      for(Storyline s : stories.values())
//      {
//          System.out.println(s.getText());
//      }
//  }
}
kjames
  • 39
  • 1
  • 7
  • There is no `adolescenceIntro()` method in this code. There is a *variable* by that name. You haven't indicated which of these too-numerous lines of code is throwing the exception. You should have provided the stack trace and the method concerned, and probably nothing else, in your question. – user207421 Nov 28 '17 at 23:20
  • Sorry-- I meant "variable" instead of "method." Changed the content of my question to make it clearer. – kjames Nov 28 '17 at 23:21
  • But you still didn't add the stack trace. – user207421 Nov 28 '17 at 23:28

1 Answers1

0

I believe your problem is with the Scanner in this piece of code here:

Scanner scr = new Scanner(System.in);
String answer = scr.nextLine();
...
scr.close();

nextLine does not block for input and throws an exception if no input has yet been entered.

You want to call hasNextLine first which will block and wait for user input:

Scanner scr = new Scanner(System.in);
if (scr.hasNextLine())
{
    String answer = scr.nextLine();
    ...
}
scr.close();

You'll encounter another problem with your code because you cannot reopen System.in once you've closed it. Create one scanner at the start of your program, re-use it and close it at the very end.


Finally, read up about how to print a stack trace and how to debug in IntelliJ (or your IDE of choice).

I also recommend writing programs incrementally - add a few lines, run it, test that it works, and repeat. It seems to me that you've written the whole thing and have expected it to work first time. That rarely happens.

Michael
  • 41,989
  • 11
  • 82
  • 128
  • 1
    perhaps it's better, based on the following https://stackoverflow.com/questions/20665769/what-causes-no-such-element-exception to instead create the Scanner object once in main and close it at the end of main instead of re-opening and closing System.in inside the nextStoryLine method... just a thought – RAZ_Muh_Taz Nov 28 '17 at 23:32
  • @RAZ_Muh_Taz Not just better - *necessary*. I was actually in the process of adding that to my answer :) – Michael Nov 28 '17 at 23:33