You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java构造方法执行后未调用的查找方法自动运行且程序崩溃问题

问题描述

我开发了一个Java程序,包含Dog类(含属性、构造方法及get/set方法)和CPanel控制面板类,该类维护Dog对象数组,支持对象的创建、查找、删除等操作。但通过CPanel创建Dog对象后,程序会自动执行Find/CheckDog方法(显示“Choose dogs name”提示),输入狗名后抛出NullPointerException崩溃。不清楚程序为何自动执行该方法及崩溃原因。

程序代码
import java.util.Scanner;

public class friendlycode2 {
  Scanner scan = new Scanner(System.in);

  public class Dog{
    int id;
    boolean deleted;
    String name;
    String breed;
    int age;
    String color; //+标准get/set方法
    
    public int GetId(){
        return id;
      }
    public boolean getDeleted(){
        return deleted;
      }
    public void setDeleted(boolean x){
        this.deleted = x;
      }
      public String getName(){
        return name;
      }  

  public Dog(int id, String name, String breed, int age, String color){
  this.name = name; this.breed = breed; this.age = age; this.color=color; this.deleted = false; 
  } 

  }
  public class CPanel{
      int nu2m;
      int Selected;
      Dog obj[ ]= new Dog[10];
  
      public CPanel(){
        System.out.println("Welcome to the dog games");       
        nu2m =0;
  }
  public void SetSelected(int x){
    this.Selected = x;
    }
    public int GetSelected(){ 
      return this.Selected;
    }
    public void CreateDog(){    //创建狗的方法
        
        System.out.println("Choose dogs name, breed, age and color \n"); 
        String userInput = scan.nextLine(); 
        String[] InputArray = userInput.split(",", 0);        
        obj[nu2m] = new Dog(nu2m, InputArray[0],InputArray[1],Integer.parseInt(InputArray[2]),InputArray[3]);        
        nu2m ++;   
        System.out.println("New dog created \n");       
        }
  public void DeleteDog(){
    CheckDog();
    obj[Selected].setDeleted(true); 
  }
  public void ShowDogs(){
    for(int i=0;i<obj.length;i++)
    {
      if(obj[i].getDeleted()==false){
        obj[i].toString();}
       else{};
      }
    }  
  public int FindDog(){
    System.out.println("Choose dogs name\n");
    String name = scan.nextLine();
    for(int i=0;i<obj.length;i++)
      {
        if(name ==obj[i].getName()){
          if(obj[i].getDeleted()==false){
        return obj[i].GetId();}
        }
        else{};
    }     
      return -1;
  }
  public void CheckDog(){
    int check = FindDog();
    if(check<0){System.out.println("Dog doesnt exist\n");}
    else{this.SetSelected(check);}    
      }
  }
    public void  mainn()  
  { 
    CPanel NewGame =new CPanel();
    String volba="0";
    System.out.println("Welcome to the dog game\n1: Create new dog\n2: Delete a dogy\n3:Show all dogs\n4:Play the game dogs\n5: Exit\n");
    while(volba!="5"){
    volba = scan.nextLine();
    switch(volba){
    case("1"):
    NewGame.CreateDog();
    case("2"):
    NewGame.DeleteDog();
    case("3"):
    NewGame.ShowDogs();
    case("4"):
    System.out.println("Ending program\n");
    //thegame(NewGame);
    }
    System.out.println("Welcome to the dog game\n1: Create new dog\n2: Delete a dogy\n3:Show all dogs\n4:Play the game dogs\n5: Exit\n");
                    }
   }   
   public static void main(String[] args) {
 friendlycode2 o = new friendlycode2();
 //o.test();
 o.mainn();
  }
}
程序输出
Welcome to the dog game
1: Create new dog
2: Delete a dogy
3:Show all dogs
4:Play the game dogs
5: Exit

1
Choose dogs name, breed, age and color 

d,e,11,d
New dog created 

Choose dogs name

d
Exception in thread "main" java.lang.NullPointerException
        at friendlycode$CPanel.FindDog(friendlycode.java:104)
        at friendlycode$CPanel.CheckDog(friendlycode.java:114)
        at friendlycode$CPanel.DeleteDog(friendlycode.java:87)
        at friendlycode.mainn(friendlycode.java:159)
        at friendlycode.main(friendlycode.java:172)
问题原因及解决方法

1. 自动执行DeleteDog的原因

mainn方法中的switch分支未添加break语句,导致执行完case("1")的CreateDog()后,会依次执行后续所有case的代码,包括case("2")的DeleteDog(),这就是创建狗后自动触发查找/删除流程的核心原因。

解决方法:在每个case分支末尾添加break:

switch(volba){
case("1"):
    NewGame.CreateDog();
    break;
case("2"):
    NewGame.DeleteDog();
    break;
case("3"):
    NewGame.ShowDogs();
    break;
case("4"):
    System.out.println("Ending program\n");
    //thegame(NewGame);
    break;
}

2. NullPointerException的原因

  • 数组越界访问:FindDog方法遍历整个长度为10的obj数组,但实际只有nu2m个位置有Dog对象,其余位置都是null,循环到null元素时调用obj[i].getName()会直接抛出空指针异常。
  • 字符串比较错误:使用==比较字符串,==判断的是对象引用而非内容,即使输入名字正确也可能匹配失败,导致循环继续访问null元素。

解决方法:

  • 限制循环范围为已创建的Dog数量,避免访问null元素;同时改用equals()比较字符串内容:
public int FindDog(){
    System.out.println("Choose dogs name\n");
    String name = scan.nextLine();
    // 只遍历已创建的狗,而非整个数组
    for(int i=0;i<nu2m;i++)
    {
        // 使用equals比较字符串内容
        if(name.equals(obj[i].getName())){
            if(!obj[i].getDeleted()){
                return obj[i].GetId();
            }
        }
    }     
    return -1;
}
  • 补充Dog构造方法的id赋值,避免GetId()返回默认值0:
public Dog(int id, String name, String breed, int age, String color){
    this.id = id; // 补充id属性赋值
    this.name = name; 
    this.breed = breed; 
    this.age = age; 
    this.color=color; 
    this.deleted = false; 
}

内容的提问来源于stack exchange,提问作者Tobukus Biblius

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:55:30