程序不会运行,Java,StringBuilder,Array

时间:2014-03-14 00:36:53

标签: java arrays stringbuilder

我想让我的程序运行。但是,我收到NullPointerException

任何帮助将不胜感激。我不想包括很多代码;所以,我只包括了日食所说的错误。

这是拼图类的构造函数。 (java.lang.NullPointerException)

我纠正了第一个问题并添加了“StringBuilder puzzle = new StringBuilder();.”我现在在同一行上得到这些错误。

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)

第55行是原始问题行。它标有“// eclipse在这一行上有错误”

代码:

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;
        }       
    }

}

测试发布在下面。它没有问题。

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);
    }

}

3 个答案:

答案 0 :(得分:3)

您的问题可能是您永远不会初始化拼图,永远不会分配给new StringBuilder()。即,

StringBuilder puzzle = new StringBuilder();  

如,

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, ' ');
            }
        }
    }
}

更重要的是,您需要学习如何调试NPE(NullPointerException)的一般概念。您应仔细检查抛出它的行,找出哪个变量为null,然后追溯到您的代码以查看原因。你会一次又一次地碰到这些,相信我。

答案 1 :(得分:1)

你遇到的问题是StringBuilder最初是空的,你不能设置一个不存在的值/字符。您尝试做的简单解决方案是使用正则表达式。

private StringBuilder puzzle;

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

答案 2 :(得分:0)

为什么会发生NullPointerExceptions?

NullPointerException是由尝试取消引用a引起的 没有指向任何东西的指针;指针为空。这是 一些可以找到NullPointerExceptions的常见场景:

  1. String myString = null;
  2. System.out.println(myString.length());
  3. 这里声明了变量myString,并在第1行初始化为null。当第2行 尝试依赖变量myString来打印 string的长度,因为myString而抛出NullPointerException 并不指向任何事情。

    1. System.out.println(aMethodThatReturnsNull().toString());
    2. 这第二个例子有点棘手。没有声明变量,但是 还有一个指针:方法的返回值 aMethodThatReturnsNull()。那个虚构的(看似毫无用处) 方法将始终返回null。正如我们在第一个例子中看到的, 尝试取消引用空指针并调用方法 引用的对象(为null)导致NullPointerException。

      如何追踪NullPointerException?

      要查找NullPointerException的来源,请从堆栈开始 跟踪。在Java控制台或日志文件中,您会看到类似的内容 这样:

      线程中的异常&#34; main&#34;显示java.lang.NullPointerException
                在com.foo.example.NullPointerExample.main(NullPointerExample.java:21)

      堆栈跟踪告诉你发生了什么(NullPointerException)和 where(NullPointerExample.java的第21行)。看看那条线,看看 如果你能识别上面给出的两种模式中的一种。问你自己 这些问题:

      1. 您是否在可能为null的变量上调用方法?
      2. 您是否在另一个方法的返回值上调用方法,其中第一个方法可能返回null?
      3. 您是否完全确定前两个问题的答案是&#34;否?&#34;
      4. NullPointerExceptions可能会发生 其他原因,但这两个是目前最常见的。

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