Need help with this code

Hello, I have created a do-while loop which is supposed to re-run if the user enters "y" or quit if the user enters "n".

It's about a number guessing game. The user must guess the computer's number and if he chooses to quit or if he guesses correctly, he's given the option to replay.The game is supposed to accept as many guesses are necessary until the number is found but when I run it I'm only able to enter one number. On the second attempt I get the error "Exception in thread "main" java.lang.NullPointerException
at Doloop2.main(Doloop2.java:60)"

Can someone help me out? I would appreciate any help.


I am posting my code hoping that it will make things clearer.

[code]

import java.util.*;

public class Doloop2
{
public static void main (String[] args)
{
final int MAX = 100;
int answer, guess, attempt = 0;
String replay = null;

Scanner scan = new Scanner (System.in);
Random generator = new Random();


answer = generator.nextInt(MAX) + 1;

System.out.print("I am thinking of a number "
+ "between 1 and 100. Enter your guess (0 to guit):");
guess = scan.nextInt();

do
{
if (guess > answer)
{
attempt++;
System.out.print ("Try a smaller number (0 to quit): ");
guess = scan.nextInt();
}
if (guess < answer)
{
attempt++;
System.out.print ("Try a bigger number (0 to quit): ");
guess = scan.nextInt();
}


if (guess == answer)
{
attempt++;
System.out.println ("You got it!");
System.out.println ("Number of total attempts:" + attempt);
System.out.println ();
System.out.print("Play again? (y/n)");

replay = scan.nextLine();

}
if (guess == 0)
{
System.out.println ("You ended the game. Play again? (y/n):");

replay = scan.nextLine();
}

}

while (replay.equals("y") || replay.equals("Y"));

}
}[/code]

Comments

  • Hey,
    The exception occurs on the line
    [code] } while (replay.equals("y") || replay.equals("Y"));[/code]
    The null pointer exception is because the [color=Blue]replay[/color] variable is set to null.

    regards
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion