for循环中的java.lang.nullpointerexception

时间:2014-09-20 22:00:14

标签: java for-loop nullpointerexception java.util.scanner multidimensional-array

我正在尝试制作一个使用Scanner类从用户那里获取输入的计划。该计划的目的是打印出时间表。在makeSchedule函数的for循环中,此行显示java.lang.NullPointerException

System.out.print(blocks[numberSchedule[i][k] - 1] + "\t");

我在函数之外测试了这行代码,它完美无缺地运行。

我不知道我错过了什么。

import java.util.Scanner;

public class Schedule
{
  public int[][] scheduleArray;
  public static String A, B, C, D, E, F, G, H;
  public static String[] blocks;

  public static void main(String[] args)

  {
    Scanner kboard = new Scanner(System.in);
    int[][] scheduleArray = new int[][] { {1, 2, 3, 1, 2, 3, 1, 2},
        {3, 1, 2, 3, 1, 2, 3, 4}, {4, 8, 6, 5, 7, 4, 8, 6},
        {8, 7, 4, 6, 5, 8, 5, 7}, {6, 5, 7, 8, 4, 6, 7, 5}};

    System.out.print("What is your A block class?");
    String A = kboard.nextLine();
    System.out.print("\n");
    System.out.print("What is your B block class?");
    String B = kboard.nextLine();
    System.out.print("\n");
    System.out.print("What is your C block class?");
    String C = kboard.nextLine();
    System.out.print("\n");
    System.out.print("What is your D block class?");
    String D = kboard.nextLine();
    System.out.print("\n");
    System.out.print("What is your E block class?");
    String E = kboard.nextLine();
    System.out.print("\n");
    System.out.print("What is your F block class?");
    String F = kboard.nextLine();
    System.out.print("\n");
    System.out.print("What is your G block class?");
    String G = kboard.nextLine();
    System.out.print("\n");
    System.out.print("What is your H block class?");
    String H = kboard.nextLine();
    System.out.print("\n");
    final String[] blocks = {A, B, C, D, E, F, G, H};

    makeSchedule(scheduleArray);

  }

  public static void makeSchedule(int[][] numberSchedule)
  {
    for (int i = 0; i < 5; i++)
    {
      for (int k = 0; k < 8; k++)
      {
        if (k != 7)
        {
          System.out.print(blocks[numberSchedule[i][k] - 1] + "\t");
        }
        if (k == 7)
        {
          System.out.println(blocks[numberSchedule[i][k] - 1] + "\n");  
        }

      }

    }
  }

}

2 个答案:

答案 0 :(得分:1)

删除final String[] final String[] blocks = {A, B, C, D, E, F, G, H};,因为您在当前范围内声明了一个新变量,并且您的静态字段从未初始化。

答案 1 :(得分:0)

您永远不会初始化您班级的public static String[] blocks;,只会初始化您主要方法的final String[] blocks = {A, B, C, D, E, F, G, H};