java - 读取文件时 Java 代码中出现 NullPointerException

标签 java exception nullpointerexception

Exception in thread "main" java.lang.NullPointerException
    at MovieSeating.assignCustomerAt(MovieSeating.java:27)
    at Assignment8.main(Assignment8.java:84)

我有一个文本文件,它读取:

  • 约翰·史密斯
  • 乔治·布什
  • 随机人
  • 第四个名字

当我在程序中名为 customerData.txt 的文本文件中调用此数据并将名称分配给二维数组中的单元格时,我收到 nullPoint 错误,并且不知道如何解决此问题。

谢谢!

<小时/>
    public class Customer
     {
       private String lastName;
       private String firstName;

       // This constructor sets the first name and last name to "???�
       public Customer()
       {
              lastName = "???";
              firstName = "???";
       }

      // This constructor constructs a Customer object  given the last name and first name
       public Customer(String customerInfo)
       {
             int space = customerInfo.indexOf(" ");
             firstName = customerInfo.substring(0, space).trim();
             lastName = customerInfo.substring(space+1).trim();

       }

       // This constructor cConstructs a Customer object using the string containing customer's info.
       // It uses the StringTokenizer to extract first name, last name, id, the number of matinee tickets,
       // and the number of normal tickets.
       public Customer(String lName, String fName)
       {
             lastName = lName;
             firstName = fName;

       }

       // This method sets the last name.
       public void setLastName(String lName)
       {
             lastName = lName;
       }
       // This method sets the first name.
       public void setFirstName(String fName)
       {
             firstName = fName;
       }

       // This method returns the last name.
       public String getLastName()
       {
             return lastName;
        }
       // This method returns the first name.
       public String getFirstName()
       {
             return firstName;
       }

       // This method checks if a customer object passed as a parameter and itself (customer object)
       // are same using their last names and first names.
       public boolean equals(Customer other)
       {
             if (lastName.equals(other.lastName) && firstName.equals(other.firstName))
                 return true;
             else
                 return false;
       }

       // This method returns a string containing a customer's initials
       // (first characters of firstName and lastName.)
       public String toString()
       {
               String result = firstName.charAt(0) + "." + lastName.charAt(0) + ".";
               return result;
       }


     } // end of the class Customer
<小时/>
    class MovieSeating 
    {
        private String[][] Seats;
        public MovieSeating(int rowNum, int columnNum)
        {
            String [][] Seats = new String[rowNum][columnNum];
            for (int r = 0; r < rowNum; r++)
            {
                for (int c = 0; c < columnNum; c++)
                {
                    Seats[r][c] = "?.?";
                }
            }
        }

        private Customer getCustomerAt(int row, int col)
        {
            System.out.println("Customer at row " + row + " and col " + col + "." );
            System.out.println(Seats[row][col]);

        }

        public boolean assignCustomerAt(int row, int col, Customer tempCustomer)
        {
            if (Seats[row][col].equals("?.?"))
            {
                tempCustomer = Seats[row][col];
                return true;
            }
            else {
                System.out.println("Seat taken..");
                return false;
            }

        }

        public boolean checkBoundaries(int row, int col)
        {
            if (col < 0 || row < 0)
            {
                return false;
            }
            else {
                return true;
            }
        }
    }
<小时/>
    import java.io.*;
    import java.util.*;

    public class Assignment8
    {
       public static void main(String[] args) throws IOException
       {

           MovieSeating theatreSeating;
           Customer tempCustomer;
           int requestedRow, requestedCol, row, col, rowNum, columnNum;
           String line, fileName;

           // to read input from a KEYBOARD.
           Scanner stdin = new Scanner(System.in);

           // Ask a user to enter a number of rows for a movie theatre seating from a KEYBOARD.
           System.out.println("Please enter a number of rows for a movie theatre seating.");
           rowNum = stdin.nextInt();

           // Ask a user to enter a number of columns for a movie theatre seating from a KEYBOARD.
           System.out.println("Please enter a number of columns for a movie theatre seating.");
           columnNum = stdin.nextInt();

           // instantiate a MovieSeating object
           theatreSeating = new MovieSeating(rowNum, columnNum);

           // get a file name read from a KEYBOARD.
           System.out.println("Please enter a file name");
           fileName = stdin.next();

           // create FileReader and BufferedReader object to
           // read from a file.
           FileReader fr = new FileReader (fileName);
           BufferedReader inFile = new BufferedReader (fr);

           /*** reading a customer's information from a FILE ***/
           line = inFile.readLine();

           /*** we will read line by line until we read the end of a given file ***/
           while (line != null)
           {
               System.out.println("\nA customer information is read from a file.");
               // printing information read from a file.
               System.out.println(line);

               // creating a customer object using information from a file
               tempCustomer = new Customer(line);

               // Ask a user to decide where to seat a customer by asking for row and column of a seat
               System.out.println("Please enter a row number where the customer wants to sit.");
               requestedRow = stdin.nextInt();
               row = requestedRow -1;

               System.out.println("Please enter a column number where the customer wants to set.");
               requestedCol =  stdin.nextInt();
               col = requestedCol -1;

               // Checking if the row number and column number are valid (exist in the theatre that we created.)
               if (theatreSeating.checkBoundaries(row, col) == false)
               {
                    System.out.println("\nrow or column number is not valid.");
                    System.out.println("A customer " + tempCustomer.getFirstName() + " " + tempCustomer.getLastName() + " is not assigned a seat.");
               }
               else
               {
                  // Assigning a seat for a customer
                  if (theatreSeating.assignCustomerAt(row, col, tempCustomer) == true)
                  {
                    System.out.println("\nThe seat at row " + row + " and column " + col + " is assigned to the customer " + tempCustomer.toString());
                    System.out.println(theatreSeating);
                  }
                  else
                  {
                    System.out.println("\nThe seat is taken.");
                  }
                }
               // Read next line in a FILE
               line = inFile.readLine();

           }//end of the while loop
             // Closing the file
           inFile.close();

         }

      }

最佳答案

在您的 MovieSeating 构造函数中,您正在隐藏 Seats 变量:

    private String[][] Seats;
    public MovieSeating(int rowNum, int columnNum)
    {
        Seats = new String[rowNum][columnNum]; //<-- remove String [][] 
        for (int r = 0; r < rowNum; r++)
        {
            for (int c = 0; c < columnNum; c++)
            {
                Seats[r][c] = "?.?";
            }
        }
    }

因此,在执行 if (Seats[row][col].equals("?.?")) 时,它会抛出 NullPointerException

关于java - 读取文件时 Java 代码中出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20213697/

相关文章:

c# - 在非 UI 线程上抛出异常时如何保留堆栈跟踪

c++ - 如何修改 C++ runtime_error 的 what 字符串?

java - MainActivity 中带有 saveText 的 Android Java NullPointerException

java - 我应该使用哪个 @NotNull Java 注释?

java - Java 中的超大型斐波那契数列

java - 通过代码编辑Linux网络配置文件("/etc/network/interfaces")

java - 在 Java 中使用 psql

java - 模拟网络断开连接以在本地测试分布式应用程序分区

java - PKIX 路径构建失败 sun.security.provider.certpath.SunCertPathBuilderException

java - 为什么我会收到空​​指针异常