【问题标题】:still having error for NullPointerException [duplicate]NullPointerException 仍然有错误[重复]
【发布时间】:2013-06-18 14:53:38
【问题描述】:

我试图调整 here 并在这里但仍然出现错误。 错误是当我想对数组中的元素做某事时想要显示它,存储元素或 使用索引搜索。这是我的代码:

import java.util.*;
public class RegisterMenu {
    private Driver[] newOwner; //array 
    private final int MAX_ITEMS = 30;
    private int size = 0;

       public RegisterMenu(){
        newOwner = new Driver[MAX_ITEMS];
        Scanner scan = new Scanner(System.in);
        System.out.println("1. Register New Car");
        System.out.println("2. Edit Car Information");
        System.out.println("3. Search Car Information");
        System.out.println("4. Display Car List");
        System.out.println("5. Exit");
        System.out.print("Enter Selection: ");
        int s = scan.nextInt();
        switch(s){
            case 1:
                System.out.println("--Register New Car--");
                Driver owner = newReg();
                newOwner[size++] = owner;                
                break;
            case 2:
                System.out.println("--Edit Car Infomation--");
                System.out.print("Enter RegNo to be edit: "); 
                int input = scan.nextInt(); //getting user input of index number which will be edited
                    if(newOwner[input].getName() == ""){
                        System.out.println("No data in RegNo "+input);
                        }
                    else{
                        Driver editOwner = newReg();
                        newOwner[input] = editOwner;
                    }
                break;
            case 3:
                System.out.println("--Search Car Infomation--");
                int index = searchReg();
                newOwner[index].toString();
                break;
            case 4:
                System.out.println("--Display Car Infomation--");
                displayReg();
                break;

            case 5:
                System.exit(0);
            default:
                System.out.println("Error selection");
        }
    }
    public Driver newReg(){ //newReg class for new registration
        Driver owner = new Driver();
        Scanner scan = new Scanner(System.in);
        owner.setRegNo(size+1); //registration number will auto update on each array
        System.out.print("Enter Name: "); //getting info from user and put in setter
        owner.setName(scan.nextLine());
        System.out.print("Enter IC: ");
        owner.setIc(scan.nextLine());
        System.out.print("Enter PlateNo: ");
        owner.carInfo.setPlateNum(scan.nextLine());
        System.out.print("Enter Color: ");
        owner.carInfo.setColor(scan.nextLine());
        System.out.print("Enter Year: ");
        owner.carInfo.setYear(scan.nextLine());
        System.out.print("Enter Make: ");
        owner.carInfo.setMake(scan.nextLine());
        System.out.print("Enter Model: ");
        owner.carInfo.setModel(scan.nextLine());
        System.out.print("Enter Capacity: ");
        owner.carInfo.setCapacity(scan.nextLine());
        return owner; //return all back
    }

    public int searchReg(){ //searchReg will return index number of array
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter Name or Ic to search: ");
        String search = scan.nextLine();
        int dataIndex = 0;
        for(int i = 0; i < newOwner.length; i++){
            if(search == newOwner[i].getIc() || search == newOwner[i].getName()){
                dataIndex = i;
            }
        }
        return dataIndex;
    }
    public void displayReg(){ //display all array
        for(int i = 0; i < newOwner.length; i++){
         System.out.println(newOwner[i].toString());
        }
    }
    public static void main (String args[]){
             while(true){
                 RegisterMenu reg = new RegisterMenu();
             }
    }
}

Car

public class Car {

    public String plateNum; //variable 
    public String make;
    public String model;
    public String color;
    public String year;
    public String capacity;

    public Car(){ //empty constructor
    }

    public Car(String plateNum, String color, String year, String make, String model, String capacity){
        this.plateNum = plateNum;
        this.color = color;
        this.year = year;
        this.make = make;
        this.model = model;
        this.capacity = capacity;
    }
    public String getPlateNum(){  //get 
        return plateNum;
    }
    public String getMake(){
        return make;
    }
    public String getModel(){
        return model;
    }
    public String getColor(){
        return color;
    }
    public String getYear(){
        return year;
    }
    public String getCapacity(){
    return capacity;
    }
    public void setPlateNum(String plateNum){ //setter
        this.plateNum = plateNum;
    }
    public void setMake(String make){
        this.make = make;
    }
    public void setModel(String model){
        this.model = model;
    }
    public void setColor(String color){
        this.color = color;
    }
    public void setYear(String year){
        this.year = year;
    }
    public void setCapacity(String capacity){
        this.capacity = capacity;
    }
}

Driver

public class Driver {  
   private int regNo; //variable
   private String name;
   private String ic;
   Car carInfo = new Car(); //calling car class

   public Driver(){ //empty constructor

   }
   public Driver(int regNo, String name, String ic, Car carInfo){ //constructor with argument
       this.regNo = regNo;
       this.name = name;
       this.ic = ic;
       this.carInfo = carInfo;
   }
   public int getRegNo(){ //get info 
       return regNo;
   }
   public String getName(){
       return name;
   }
   public String getIc(){
       return ic;
   }
   public void setRegNo(int regNo){ //set from user
       this.regNo = regNo;
   }
   public void setName(String name){
       this.name = name;
   }
   public void setIc(String ic){
       this.ic = ic;

   }
   public String toString(){ //to string for display
       return "RegNo: "+getRegNo()+"\t\tName: "+getName()+"\t\tIc: "+getIc()+
               "\t\tPlateNo: "+carInfo.getPlateNum()+"\t\tColor: "+carInfo.getColor()+"\t\tYear: "+carInfo.getYear()+
                       "\t\tMake: "+carInfo.getMake()+"\t\tModel: "+carInfo.getModel()+"\t\tCapacity: "+carInfo.getCapacity()+"cc";
   }
}

【问题讨论】:

  • 在这种情况下,堆栈跟踪真的很有帮助。请将其添加到您的问题中。
  • if(newOwner[input].getName() == "")。不要使用 == 比较字符串的内容。
  • 作为问题的旁注,您最好重复使用 RegisterMenu 对象,方法是:RegisterMenu reg = new RegisterMenu(); while(true){ reg.interactiveRecordImport(); } 这样您就可以避免在每次迭代时重新实例化该对象,并且为了以后的改进,您将能够使其以某种方式存储结果。
  • 这个帖子最好放在code review上吗?

标签: java arrays class loops switch-statement


【解决方案1】:

您在main 方法中反复创建新的RegisterMenu 对象

while (true) {
   RegisterMenu reg = new RegisterMenu();
}

在此处有效地“擦除”数组newOwner 的任何先前内容:

newOwner = new Driver[MAX_ITEMS];

因此在displayReg 中,数组为空,导致NPE。即使数组包含一些个元素,也没有检查来确保当前元素不是null

要立即修复,您需要使用 RegisterMenu 的单个实例和

for (int i = 0; i < newOwner.length; i++) {
    if (newOwner[i] != null) {
        System.out.println(newOwner[i].toString());
    }
}

但是可以通过使用ArrayList 来消除这种保护检查。

注意:当前 IDE 中的调试器非常适合解决此类问题

【讨论】:

  • 谢谢!这真的对我有很大帮助!我只是将 while(true) 循环放在 RegisterMenu() 中,而不是放在 main 方法中,而不是像冠军一样工作:)
【解决方案2】:

每次访问 newOwner 数组时,我都看不到对索引变量的单一控制。举个例子:

int input = scan.nextInt(); //getting user input of index number which will be edited
if(newOwner[input].getName() == ""){

您完全确定input 索引与现有用户相关吗?如果不是,newOwner[index] 返回 null,当你调用 getName 时,你会得到一个 NPE。

您正确定义了数组,但您只是按需创建和添加新元素:

case 1:
    System.out.println("--Register New Car--");
    Driver owner = newReg();
    newOwner[size++] = owner;                
    break;

你的第一次初始化是这样的:

newOwner = new Driver[MAX_ITEMS];

分配一个长度合适但填充有null 元素的数组。您需要确保您没有访问空所有者,例如,在获取元素之前进行空检查(另外,进行范围检查以避免越界异常)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-14
    • 2019-01-05
    • 2016-04-03
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多