質問

I am trying to get my program to run. However, I am getting a NullPointerException.

Any help would be appreciated. I didn't want to include to much code; so, I only included the block that eclipse said was wrong.

This is the constructor for the puzzle class. (java.lang.NullPointerException)

I corrected the first problem and added "StringBuilder puzzle = new StringBuilder();." I now get these errors on the same line.

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.AbstractStringBuilder.setCharAt(Unknown Source)
at java.lang.StringBuilder.setCharAt(Unknown Source)
at Puzzle.<init>(Puzzle.java:55)
at PuzzleGameConsole.main(PuzzleGameConsole.java:22)

Line 55 is the original problem line. It's marked with "//eclipse had an error on this line"

code:

public class Puzzle
{

    private StringBuilder puzzle;

    public Puzzle(String theSolution)
    {
        for (int index = 0; index < theSolution.length(); index++) 
        {
            if (theSolution.charAt(index) != ' ') 
            {
                puzzle.setCharAt(index, '-');  //eclipse had an error on this line
            }
            else if (theSolution.charAt(index) == ' ')
            {
                puzzle.setCharAt(index, ' ');
            }
        }
    }
}


public int guessLetter(char letter)
    {   
        int count = 0;

        for(int index = 0; index < solution.length(); index++)
        {
            if(Character.toUpperCase(letter) == solution.toUpperCase().charAt(index))
            {
                if (puzzle.charAt(index) == '-') 
                {
                    puzzle.setCharAt(index, letter);
                }
                else
                {
                    count = 0;
                    break;
                }
                count++;
            }
        }
        return count;
    }

    public String getPuzzle()
    {
        return "";
    }


    public boolean solvePuzzle(String guess)
    {
        if(guess.toUpperCase().equals(solution.toUpperCase()))
        {
            return true;
        }
        else
        {
            return false;
        }       
    }

}

The test is posted below. It has no problems.

import java.util.Arrays;
import java.util.Scanner;


public class PuzzleGameConsole
{
    private static final String NEWLINE = "\n";
    private static final String MENU = "(1) GUESS A LETTER (2) SOLVE THE PUZZLE (3) QUIT >> ";
    private static final String PROMPT_ENTER_LETTER = "\nENTER A LETTER> ";
    private static final String PROMPT_SOLVE_PUZZLE = "\nSOLVE THE PUZZLE> ";

    private static final int SELCTION_ENTER_LETTER = 1;
    private static final int SELCTION_SOLVE_PUZZLE = 2;
    private static final int SELCTION_QUIT = 3;


    public static void main(String[] args) 
    {

        Scanner in = new Scanner(System.in);

        Puzzle puzzle = new Puzzle("JAVA IS FUN");


        int selection = 0;

        while(selection != SELCTION_QUIT)
        {
            System.out.printf("PUZZLE: %s\n\n", puzzle.getPuzzle());

            System.out.print(MENU);
            selection = in.nextInt();
            in.nextLine();

            if(selection == SELCTION_ENTER_LETTER)
            {
                System.out.print(PROMPT_ENTER_LETTER);
                char letter = in.next().charAt(0);

                int letterCount = puzzle.guessLetter(letter);
                if(letterCount > 0)
                {
                    printMessageBox(String.format("YES! The letter %s was found %d time(s).", letter, letterCount));
                }
                else
                {
                    printMessageBox(String.format("Sorry, the letter %s is not available in the puzzle.", letter));                 
                }
            }
            else if(selection == SELCTION_SOLVE_PUZZLE)
            {
                System.out.print(PROMPT_SOLVE_PUZZLE);
                String guess = in.nextLine();

                if(puzzle.solvePuzzle(guess))
                {
                    printMessageBox("Congratulations, you solved the puzzle!"); 
                    selection = 3;
                }
                else
                {
                    printMessageBox(String.format("Sorry, '%s' is not the puzzle.  Keep trying!", guess));
                }
            }
            else if (selection != SELCTION_QUIT)
            {
                System.out.println("INVALID MENU OPTION");
            }
        }

        System.out.println("\nGood Bye!");

        in.close();
    }

    public static void printMessageBox(String message)
    {
        char [] border = new char[message.length() + 4];
        Arrays.fill(border, '-');

        StringBuilder result = new StringBuilder();
        result.append(NEWLINE);
        result.append(border).append(NEWLINE);
        result.append("| ").append(message).append(" |").append(NEWLINE);
        result.append(border).append(NEWLINE);

        System.out.println(result);
    }

}
役に立ちましたか?

解決 2

The problem you have is that StringBuilder is initially empty and you can't set a value/character which doesn't already exist. The simple solution to what you are attempting to do is to use a regex.

private StringBuilder puzzle;

Puzzle(String theSolution) {
    // create a buffer where all non space are turned into -
    puzzle = new StringBuilder(theSolution.replaceAll("\\S", "-"));
}

他のヒント

Your problem is likely that you never initialize puzzle, never assign to it a new StringBuilder(). i.e.,

StringBuilder puzzle = new StringBuilder();  

e.g.,

public class Puzzle
{
    private StringBuilder puzzle = new StringBuilder(); // **** add this!

    public Puzzle(String theSolution)
    {
        for (int index = 0; index < theSolution.length(); index++) 
        {
            if (theSolution.charAt(index) != ' ') 
            {
                puzzle.setCharAt(index, '-');  //eclipse had an error on this line
            }
            else if (theSolution.charAt(index) == ' ')
            {
                puzzle.setCharAt(index, ' ');
            }
        }
    }
}

More importantly, you need to learn the general concepts of how to debug a NPE (NullPointerException). You should inspect the line carefully that throws it, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me.

Why do NullPointerExceptions happen?

A NullPointerException is caused by an attempt to dereference a pointer that doesn't point to anything; the pointer is null. Here are a couple of common scenarios where NullPointerExceptions can be found:

  1. String myString = null;
  2. System.out.println(myString.length());

Here a variable, myString, is declared and initialized to null on line #1. When line #2 attempts to deference the variable myString in order to print the string's length, a NullPointerException is thrown because myString doesn't point to anything.

  1. System.out.println(aMethodThatReturnsNull().toString());

This second example is a little trickier. No variable was declared, but there is still a pointer: the return value of the method aMethodThatReturnsNull(). That fictitious (and seemingly useless) method will always return null. As we saw in the first example, attempting to dereference a null pointer and call a method on the referenced object (which is null) results in a NullPointerException.

How do you track down a NullPointerException?

To find the source of a NullPointerException, start with the stack trace. In your Java console or log file, you'll see something like this:

Exception in thread "main" java.lang.NullPointerException
at com.foo.example.NullPointerExample.main(NullPointerExample.java:21)

The stack trace tells you what happened (NullPointerException) and where (line 21 of NullPointerExample.java). Look at that line and see if you can recognize one of the two patterns given above. Ask yourself these questions:

  1. Are you calling a method on a variable that might be null?
  2. Are you calling a method on the return value of another method, where the first method might return null?
  3. Are you absolutely sure the answer to the first two questions was "no?"

NullPointerExceptions can happen for other reasons, but these two are by far the most common.

http://publicint.blogspot.com/2009/04/nullpointerexception.html

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top