我想简单地循环遍历对象的所有值,就像我使用数组的值一样。我在网上搜索过,但他们似乎总是比我能理解的复杂得多。我的代码非常简单地显示了我想做什么。
这是我的代码:
class myCON{
int modelYear;
String modelName;
public myCON(int year, String name){
modelYear = year;
modelName = name;
}
public static void main(String[] args){
/*
***********************************************************
int[] arr= {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
for ( int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
System.out.println("end");
*************************************************************
*/
myCON myObj1 = new myCON(2005, "Nissan5");
myCON myObj2 = new myCON(2006, "Nissan6");
myCON myObj3 = new myCON(2007, "Nissan7");
myCON myObj4 = new myCON(2008, "Nissan8");
myCON myObj5 = new myCON(2009, "Nissan9");
for(int i=1; i<6;i++){
System.out.println(myObj[i].modelYear + " " + myObj[i].modelName);
}
System.out.println(myObj1.modelYear + " " + myObj1.modelName);
System.out.println(myObj2.modelYear + " " + myObj2.modelName);
System.out.println(myObj3.modelYear + " " + myObj3.modelName);
System.out.println(myObj4.modelYear + " " + myObj4.modelName);
System.out.println(myObj5.modelYear + " " + myObj5.modelName);
}
}
最佳答案
将它们存储在数组中,然后可以对其进行迭代。
像这样:
myCON myObj[] = {new myCON(2005, "Nissan5"), new myCON(2006, "Nissan6")}
for(int i=0; i<myObj.length;i++){
System.out.println(myObj[i].modelYear + " " + myObj[i].modelName);
}