简体   繁体   English

如何修复我的空指针异常

[英]How do I fix my null pointer exception

Doing a code for a class assignment, and im getting null pointer exception on these lines(bolded and italicized in my code): I don't understand how these lines are pointing at a blank spot, like the first one is my code trying to set a name for a certain seat, but apparantly i can't because it is null, even though i have i set to 0, first name set to an empty string, etc. helP! 为类分配代码,并在这些行上获得空指针异常(在我的代码中用粗体和斜体表示):我不明白这些行是如何指向空白的,就像第一个是我的代码试图设置某个座位的名称,但是显然我不能,因为它为null,即使我将我设置为0,将名字设置为空字符串,等等。helP!

public class Passenger {
    String FirstName;
    String LastName;

    void getName() {
        FirstName = " ";
        LastName = " ";
    }

    void getName(String first, String last) {
        FirstName = first;
        LastName = last;
    }

    String getFirst() {
        return FirstName;
    }

    String getLast() {
        return LastName;
    }

    void setFirstName(String tempfirst) {
        FirstName = tempfirst;
    }

    void setLastName(String templast) {
        LastName = templast;
    }

    void printNames() {
        System.out.printf("%s %s\n", this.getFirst(), this.getLast());
    }

    public static void main(String[] args) {
    }
}

public class WaitingList extends Passenger {
    Passenger[] waitlist = new WaitingList[10];

    WaitingList(){
        for(int i = 0; i<10;i++){
            ***waitlist[i].setFirstName("");***
            waitlist[i].setLastName("");
        }}

    void printWaitingList() {
        for (int j = 0; j < 10; j++)
            waitlist[j].printNames();
    }

    void setPassenger(int i, Passenger tempPass) {
        waitlist[i] = tempPass;
    }

    Passenger getPassenger(int i) {
        return waitlist[i];
    }

    public static void main(String[] args) {
    }

}

import java.io.Console;
import java.util.Scanner;

public class SeatingChart extends WaitingList {
    Passenger[][] pass = new Passenger[10][4];

    SeatingChart() {
        for (int row = 0; row < 10; row++) {
            for (int col = 0; col < 4; col++) {
                pass[row][col] = new Passenger();
            }
        }
    }

    void printSeatingChart() {
        for (int row = 0; row < 10; row++) {
            for (int col = 0; col < 4; col++) {
                System.out.print(pass[row][col].getFirst() + "\t");
                System.out.print(pass[row][col].getLast() + "\n");
            }
        }
    }

    String getSeatChoicefromUser() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter preferred seat (row, column): ");
        String seat = scanner.next();
        return seat;
    }

    void setPassenger(int row, int col, Passenger temppass) {
        pass[row][col] = temppass;
    }

    Passenger getPassenger(int row, int col) {
        return pass[row][col];
    }

    Passenger search(String first, String last) {
        Passenger search = new Passenger();
        for (int row = 0; row < 10; row++) {
            for (int col = 0; col < 4; col++) {
                String tempfirst = pass[row][col].getFirst();
                String templast = pass[row][col].getLast();
                if (tempfirst.equals(first)) {
                    if (templast.equals(last)) {
                        search = pass[row][col];
                        removePassenger(row, col);
                    }
                } else {
                    search = null;
                    System.out.print("\nPassenger not found\n");
                }
            }
        }
        return search;
    }

    void removePassenger(int row, int col) {
        pass[row][col].setFirstName(null);
        pass[row][col].setLastName(null);
    }

    Passenger reconcileWithWaitingList() {
        int i = 0;
        Passenger pass = new Passenger();
        String tempfirst = waitlist[i].getFirst();
        String templast = waitlist[i].getLast();
        if (tempfirst.equals(null)) {
            if (templast.equals(null))
                System.out.print("\nWaiting list is empty\n");
        } else {
            pass = waitlist[i];
            for (i = 0; i < 10; i++)
                waitlist[i] = waitlist[i + 1];
        }
        return pass;
    }

    public void addPassengerToWaitingList(int wrow, int wcol) {
        Passenger addPass = new Passenger();
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter first name: ");
        String tempfirst = sc.next();
        System.out.print("Enter last name: ");
        String templast = sc.next();
        addPass = search(tempfirst, templast);
        if (addPass == null) {
            String tempfirst1 = pass[wrow][wcol].getFirst();
            String templast1 = pass[wrow][wcol].getLast();
            if (tempfirst1.equals(null)) {
                if (templast1.equals(null)) {
                    pass[wrow][wcol].setFirstName(tempfirst1);
                    pass[wrow][wcol].setLastName(templast1);
                }
            }
        } else
            System.out.print("Passenger already present!");
    }

    public static void main(String[] args) {
    }
}

Your waitlist array holds null elements. 您的等待列表数组包含空元素。 You must first initialize the elements before trying to use them. 您必须先初始化元素,然后再尝试使用它们。

Passenger[] waitlist = new WaitingList[10];

WaitingList(){
    for(int i = 0; i<10;i++){
       waitlist[i] = new WaitingList();  // *** first create an element 
       waitlist[i].setFirstName("");   // *** before using it.
       waitlist[i].setLastName("");
    }
}

Think of an object array similar to a parking lot. 想一想类似于停车场的对象阵列。 When you create the array that is equivalent to creating the lot, and at first the lot, though it holds a lot of spaces, is empty. 当您创建与创建批次相同的数组时,尽管批次拥有很多空间,但最初批次是空的。 You can't drive any cars in the lot until you first put cars in the lot. 在您第一次汽车放入卡车之前,您不能驾驶任何汽车。 Likewise, you can't use any of the array items until they refer to honest to goodness objects. 同样,您不能使用任何数组项,除非它们引用诚实对象。


Edit 编辑
Regarding your comment, 关于您的评论,

that gave me a stack overflow error on the same line 在同一行上给了我一个堆栈溢出错误

That's a whole new error -- you've got some recursive code in there. 这是一个全新的错误-您那里有一些递归代码。 That problem is due to this code: 该问题是由于以下代码引起的:

public class WaitingList extends Passenger {
   Passenger[] waitlist = new WaitingList[10];
  • First off, a WaitingList should not be a subclass of a Passenger. 首先,WaitingList不应是旅客的子类。 This makes no sense since the concept of a waiting list is not a specialized case of the concept of a passenger. 这没有意义,因为候补名单的概念不是乘客概念的特殊情况。 In other words, it does not fulfill the "is-a" criteria for inheritance. 换句话说,它不满足继承的“是”标准。 Rather it fulfills the "has-a" criteria -- a waiting list has passengers, not is-a passenger. 相反,它满足“具有”标准-等候名单上有乘客,而不是-乘客。 So use composition instead. 因此,请改用合成。
  • Next the WaitingList class should not create and fill an array of WaitingLists as this will cause infinite recursion with each new WaitingList object creating 10 new WaitingList objects, each of which will create 10 more WaitingList objects, each of which will... do you see the problem? 接下来,WaitingList类不应创建并填充WaitingLists数组,因为这将导致无限递归,每个新的WaitingList对象将创建10个新的WaitingList对象,每个对象将创建10个以上WaitingList对象,每个对象将...问题? Instead the WaitingList class should likely inherit from no other classes, and should hold an array (or ArrayList) of Passenger objects, not WaitingList objects. 相反,WaitingList类可能不应该继承自其他任何类,并且应包含一个Passenger对象而不是WaitingList对象的数组(或ArrayList)。

Your code has lots of problems and you may wish to restart this project. 您的代码有很多问题,您可能希望重新启动该项目。

在此处输入图片说明


Hey you declared array of references What you need to do is initialize those null references before using them 嘿,您声明array of references您需要做的是在使用它们之前初始化这些空引用

for(int i=0; i< waitlist.length;++i){
    waitlist[i] = new waitlist();
}

then call your function 然后调用你的函数

Replace your Passenger class code with it. 用它替换您的乘客舱代码。 Have Fun :) 玩得开心 :)

 public class Passenger {
        String FirstName = "";
        String LastName = "";
        void getName(){
            FirstName="";
            LastName="";}
        void getName(String first, String last){
            if(first != null)
            {    
                 FirstName=first;
            }
         else
         {
           FirstName = "";
         }
         if(last != null)
         {
            LastName=last;
         }
         else
         {
           LastName = "";
         }
        }
        String getFirst(){
            return FirstName;}
        String getLast(){
            return LastName;}
        void setFirstName(String tempfirst){
           if(tempfirst == null)
           {
             FirstName = "";
           }
           else
           {        
             FirstName=tempfirst;
           }
        }
        void setLastName(String templast){
           if(templast == null)
           {
             LastName="";
           }
           else
           {
            LastName=templast;
           }
        }
        void printNames(){
            System.out.printf("%s %s\n", this.getFirst(), this.getLast());
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM