JAVA的对象数组赋值,纠结了。。。52
发布网友
发布时间:2023-11-22 09:08
我来回答
共2个回答
热心网友
时间:2024-12-03 17:05
楼上正解,我在这里给你另外一种赋值方式,供你参考。首先class DVD1中的代码生成get和set方法。然后通过实例化对象,去赋值,代码如下
public static void main(String[] args) {
DVD1[] manager = new DVD1[6];
//实例化一个对象
DVD1 dvd1 = new DVD1();
dvd1.setName("罗马假日");
dvd1.setDate("1日");
dvd1.setState("可借");
dvd1.setTimes(10);
manager[0] = dvd1; //给数据对象赋值
//实例化一个对象
DVD1 dvd2 = new DVD1();
dvd2.setName("java编程");
dvd2.setDate("null");
dvd2.setState("可借");
dvd2.setTimes(11);
manager[1] = dvd2; //给数据对象赋值
//实例化一个对象
DVD1 dvd3 = new DVD1();
dvd3.setName("面向对象");
dvd3.setDate("null");
dvd3.setState("可借");
dvd3.setTimes(1);
manager[2] = dvd3; //给数据对象赋值
}
class DVD1{
String name;
String state;
String date;
int times;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getTimes() {
return times;
}
public void setTimes(int times) {
this.times = times;
}
}
追问不错不错,,,感谢感谢。。。
热心网友
时间:2024-12-03 17:05
应为你没有对数组的元素初始化,new一下就行了
class OOP {
public static void main(String[] args) {
DVD1[] manager = new DVD1[6];
for (int i = 0; i < manager.length; i++) {
manager[i] = new DVD1();
}
manager[0].name = "罗马假日";
manager[0].date = "1日";
manager[0].state = "可借";
manager[0].times = 10;
manager[1].name = "java编程";
manager[1].date = "null";
manager[1].state = "可借";
manager[1].times = 11;
manager[2].name = "面向对象";
manager[2].date = "null";
manager[2].state = "可借";
manager[2].times = 1;
}
}
追问那我要他输入的显示出来,我用的是for循环,现在怎么值是
test1.DVD2@1aa9f99
test1.DVD2@d42d08
test1.DVD2@1d86fd3
这些玩意儿啊!!!搞不懂。。。。。拜托啦。。。
追答
这个是调用了Object里面的toStirng().默认的是
return getClass().getName() + "@" + Integer.toHexString(hashCode());
友好的显示,方法很多,我比价喜欢override toString();
class DVD1 {
String name;
String state;
String date;
int times;
public String toString() {
return "{" + name + "," + state + "," + date + "," + times + "}";
}
}