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

stuck in the jar game android

when i run the project, it gives me that message: "Exception in thread "main" java.lang.NullPointerException at Game.main(Game.java:15)" So what should i do?? that's my code in java....

import java.io.Console;
import java.util.Scanner;
import java.util.Random;

public class Game {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int number = 0;
           System.out.println("ADMINISTRATOR SETUP");
           System.out.println("======================");
           Console console = System.console();
           Scanner in = new Scanner(System.in);
           String nameOfItem = console.readLine("Name of items in the jar: ");
           System.out.printf("Maximum number of %s in the jar: ", nameOfItem);
           int numberOfItem = in.nextInt();
           Random random = new Random();
           int randomNumber = random.nextInt() + 1;
           System.out.println("");
           System.out.println("Player");
           System.out.println("======================");
           System.out.println("Your goal is to guess how many"+ nameOfItem +"are in the jar. Your guess sould be between 1 and " + numberOfItem);
           System.out.println("");
           System.out.println("Ready? ");
           System.out.println("");
           int guessedNumber;
           do {
               guessedNumber = in.nextInt();
               System.out.printf("Guess: %d", guessedNumber);
               number += 1;
            } while(guessedNumber != randomNumber);
            if (guessedNumber == randomNumber){
                guessedNumber = randomNumber;
            }
            System.out.println("Congradulations - you guessed that there are"+ guessedNumber +" "+ nameOfItem +" in the jar! It took you "+ number +" guess(es) to get it right.");
        }

    }

1 Answer

I think your problem is from mixing console.readline and the scanner. The scanner probably never consumed the input from the readline. Java is not too simple when it comes to console input.