Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures Efficiency! Menu UI

Oussama DJEDIDI
Oussama DJEDIDI
4,599 Points

java.lang.NullPointerException at com.teamtreehouse.KaraokeMachine.promptAction(KaraokeMachine.java:27)

When running (run time error)

Exception in thread "main" java.lang.NullPointerException
at com.teamtreehouse.KaraokeMachine.promptAction(KaraokeMachi ne.java:27)
at com.teamtreehouse.KaraokeMachine.run(KaraokeMachine.java:4 0)
at Karaoke.main(Karaoke.java:10)

Florian Tönjes
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Florian Tönjes
Full Stack JavaScript Techdegree Graduate 50,856 Points

How does the code look that you are trying to run? Click on "Markdown Cheatsheet" when you are writing a post here, to see how you can include your code in a visual appealing style.

5 Answers

Jason Wolfe
PLUS
Jason Wolfe
Courses Plus Student 12,908 Points

Check your code for:

mReader = new BufferedReader(new InputStreamReader(System.in));

In the KaraokeMachine constructor. If mReader isn't initialized there, then it will throw a null.

It is hard to tell what the exact problem is without seeing any code, but from looking at your error it looks like your program is trying to pull info from a variable or method that doesn't have any data in it.

Oussama DJEDIDI
Oussama DJEDIDI
4,599 Points

This is the function for the Java course : The error is displayed for

choice = promptAction();
package com.teamtreehouse;

import com.teamtreehouse.model.Song;
import com.teamtreehouse.model.SongBook;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.util.List;
import java.util.HashMap;
import java.util.Map;

public class KaraokeMachine {
  private SongBook mSongBook;
  private BufferedReader mReader;
  private Map<String, String> mMenu;

  public KaraokeMachine(SongBook mSongBook) {
    mSongBook = mSongBook;
    mReader = new BufferedReader(new InputStreamReader(System.in));
    mMenu = new HashMap<String, String>();
    mMenu.put("add", "Add a new song to the menu");
    mMenu.put("quit", "Give up. Exit the program");
  }

  private String promptAction() throws IOException {
    System.out.printf("There are %d songs available. Your options are: %n", mSongBook.getSongCount());
    for (Map.Entry<String, String> option : mMenu.entrySet()){
      System.out.printf("%s - %s %n", 
                        option.getKey(), option.getValue());
    }
    System.out.print("What do you want to do: ");
    String choice = mReader.readLine();
    return choice.trim().toLowerCase();
  }

  public void run (){
    String choice = "";
    do {
      try {
        choice = promptAction();
        switch (choice) {
          case "add":
          Song song = promptNewSong();
          mSongBook.addSong(song);
          System.out.printf("%s added. %n%n", song);
          break;
          case "quit":
          System.out.print("Thanks for playing");
          break;
          default:
          System.out.printf("Unknown choice: %s. Try again%n", choice);
        }
      }catch(IOException ioe){
        System.out.println("Problem with input");
        ioe.printStackTrace();
      } 
    }while(!choice.equals("quit"));
  }
  private Song promptNewSong() throws IOException {
    System.out.print("enter the artist's name:");
    String artist = mReader.readLine();
    System.out.print("enter the title:");
    String title = mReader.readLine();
    System.out.print("enter the video url:");
    String videoUrl = mReader.readLine();
    return new Song(artist, title, videoUrl);
  }

  private int promptFroIndex(List<String> options) throws IOException {
    int counter = 1;
    for(String option : options){
      System.out.printf("%d.) %s %n", counter, option);
      counter ++;
    }
    String optionAsString = mReader.readLine();
    int choice  = Integer.parseInt(optionAsString.trim());
    System.out.printf("Your choice %d", choice);
    return choice - 1;
  }

}
Matt Y
Matt Y
1,595 Points

Check mSongBook = songBook;

Phil Spelman
Phil Spelman
6,664 Points

I had this same error. My code is essentially identical to Oussama DJEDIDI's code. Here's my setup and what I figured out using JShell (available as of Java 9).

This was on Windows 10 I was using IntelliJ to follow along with Craig's lesson and write the code along with him. In IntelliJ I was using a JShell environment through the IntelliJ Terminal (I replaced the default IntelliJ Terminal with the windows MINGW32 terminal that I was using to learn Git stuff)

For the commands that Craig writes in the java-repl, I wrote those in a file called "junks.java," which I saved in the same folder as my Karaoke.java and KaraokeMachine.java files (the root of my project)

I changed the terminal directory to the folder in which my Karaoke.java file was stored and THEN I opened JShell by typing "jshell" I have a file called "junks.java" and in that file I have written all my jshell commands for opening the .java files I made from following Craig's lesson:

JShell opens and I type: /open junks.java

///////////////junks.java FILE STARTS HERE/////////////////////

/open model/Song.java
/open model/Songbook.java
/open KaraokeMachine.java
System.out.printf("Print this!%n");

        //MAKE A NEW MACHINE
Songbook songbook = new Songbook("BOOK ONE!");

Song song = new Song(
    "Michael Jackson",
    "Beat It",
    "https://www.youtube.com/watch?v=SaEC9i9QOvk");
System.out.printf("Adding %s %n",song);
songbook.addSong(song);
System.out.printf("There are %d songs in the book.%n", songbook.getSongCount());

KaraokeMachine machine = new KaraokeMachine(songbook);


///////////////FILE ENDS HERE/////////////////////

In the JShell terminal I saw the following:

jshell> /open junks.java Print this! Adding Song: Beat It by Michael Jackson There are 1 songs in the book.

I TRIED TO MAKE A NEW MACHINE AND CALL "machine.run()" AND GOT THE FOLLOWING ERROR

jshell> Songbook songbook = new Songbook("Book three"); songbook ==> Book: Book three

jshell> KaraokeMachine machine = new KaraokeMachine(songbook) machine ==> KaraokeMachine@18a70f16

jshell> machine.run() There are 0 songs available. Your options are: add - Add a new song to the songbook quit - Give up. Exit program What do you want to do (type your answer): | java.lang.NullPointerException thrown: | at KaraokeMachine.promptAction (#792:33) | at KaraokeMachine.run (#792:42) | at (#816:1)

I double and triple checked my code, which had worked previously, and there were no mistakes that I could see.

I figured there might have been some hangup with objects in memory that I had created through messing around with JShell, so I QUIT and began a new instance:

jshell> /exit | Goodbye

phil_@DESKTOP-88PHKT2 MINGW32 ..javabasics/src/javaintermediate/karaoke (treehouse_rewrite) $ jshell | Welcome to JShell -- Version 9 | For an introduction type: /help intro

HERE'S WHERE I TRIED THIS AGAIN

jshell> /open junks.java Print this! Adding Song: Beat It by Michael Jackson There are 1 songs in the book.

jshell> machine.run() There are 1 songs available. Your options are: add - Add a new song to the songbook quit - Give up. Exit program What do you want to do (type your answer):

AND IT WORKED!

I have no idea if that will help anyone, but that's how I figured out that my code was typed correctly!