Java - Null指针输入异常,99瓶啤酒示例

时间:2014-09-10 02:04:28

标签: java nullpointerexception

我正在学习Java,并尝试制作一瓶99瓶啤酒'程序。当我将瓶数硬编码为99(整数)时,代码正确执行。当我要求瓶子的用户输入和parseInt输入到int时,我得到一个空指针异常。

来源:

package beersong;

import java.io.Console;

/**
 *
 * @author andrewjohnson
 */
public class BeerSong {

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    Console c = System.console();

    Wall x = new Wall();
    //System.out.println("How many bottles of beer are on the wall?");
    String userInput = c.readLine("How many bottles of beer are on the wall?");
    x.numOfBottles = Integer.parseInt(userInput);
    //x.numOfBottles = 99;
    x.drinkBeer();
  }
}

我的Wall()对象:

package beersong;

/**
 *
 * @author andrewjohnson
 */
public class Wall {

  int numOfBottles;

  public int takeOneDown() {
    numOfBottles = numOfBottles - 1;
    return numOfBottles;
  }

  public int drinkBeer() {
    while (numOfBottles > 0) {
      if (numOfBottles == 1) {
        System.out.println(numOfBottles + " bottle of beer on the wall,");
        System.out.println("Take it down, pass it around, ");
        takeOneDown();
        System.out.println(numOfBottles + " bottles of beer on the wall!");
        System.out.println("\n");

      } else {
        System.out.println(numOfBottles + " bottles of beer on the wall,");
        System.out.println("Take one down, pass it around, ");
        takeOneDown();
        System.out.println(numOfBottles + " bottles of beer on the wall!");
        System.out.println("\n");
      }
    }
    return numOfBottles;
  }
}

我已经广泛搜索了这个问题并且无法找到问题。我相信这是我要求输入的方式,但我不确定,我对Console()对象了解不多。

0 个答案:

没有答案