我正在尝试从对象数组中删除一个对象,但是我似乎无法让它正常工作。我是 java 新手,注意到你不能简单地对数组执行 .remove() 。我知道你可以使用ArrayList,但是有没有办法从java中的数组中删除元素?我知道从技术上讲你无法做到这一点,因为数组是固定长度的,所以我所做的是将值 null 分配给数组中的对象引用。这是可行的,但是当我打印数组时,我收到此错误。
错误
java.lang.NullPointerException
对象定义
public class Dog {
//Iniatilising instance variables
private String name;
private String breed;
private Gender gender;
private int age;
...
测试类常量
public class TestDog {
//Create a constant value for MAX
static final int MAX = 10;
//Define a constant PROMPT
static final String PROMPT = "---->";
//Define a constant SPACES
static final String SPACES = " ";
//String array of menu options
static final String options[] = {"Add new Dog","Display details for a Dog",
"Update details for a Dog","List all Dogs","Delete all Dogs","Delete one Dog","Quit"};
//Define a constant QUIT
static final int QUIT = options.length;
//Create an array capable of managing up to MAX Dog instances
static Dog pets[] = new Dog[MAX];
static Dog empty[] = new Dog[MAX];
//Define a value 'count' to indicate number of objects in array
static int count = 0;
//A menu title
static String title = "Dog Manager";
//Define a menu using title & options
static Menu myMenu = new Menu(title,options);
//Define a Scanner
static Scanner input = new Scanner(System.in);
测试类删除方法
public static void deleteOneDog() {
System.out.println("\nOK - Delete one dog");
boolean noDogs = false;
if (count == 0) {
System.out.println(PROMPT+"Sorry, there are no dogs.");
noDogs = true;
}
LEATH
胡子哥哥
慕工程0101907
相关分类