我很困惑为什么我的Object数组仍然相同。我试图从数组中计算索引。我如何计算指数?
public class TryArray {
Students[] arr;
public void add(Students std) {
for (int i = 0; i < arr.length ; i++) {
arr[i] = std;
System.out.println(std); //it willbe more than one time displayed
break;
}
}
public TryArray(int lengthOfArray) { //Constructor for the length Array
arr = new Students[lengthOfArray];
}
}
这是我的主要课程test1.java
public class test1 {
public static void main(String[] args) {
TryArray val = new TryArray(4);
Students a1 = new Students(1, "Bob", "Julius");
Students a2 = new Students(2, "Joe", "Chris");
Students a3 = new Students(3, "Christian", "Henderson");
Students [] arr = {a1,a2,a3};
val.add(a1);
val.add(a2);
val.add(a3);
}
}
预期输出:
1, Bob, Julius
2, Joe, Chris
3, Christian, Henderson
我错过了什么吗?
答案 0 :(得分:1)
您当前的代码中存在很多误解。首先,您要使用要添加的元素设置数组的所有元素。其次,在add
方法中,您可以在不考虑正确结果的情况下打印变量乘以数组长度。
TryArray
类的代码可能会被重写为:
public class TryArray {
//array to store the students (elements)
private Students[] arr;
//counter of how many students are stored by this instance
private int size;
public void add(Students std) {
/*
the code here makes no sense, see explanation above
for (int i = 0; i < arr.length ; i++) {
arr[i] = std;
System.out.println(std); //it willbe more than one time displayed
break;
}
*/
if (size < arr.length) {
arr[size++] = std;
//this is for testing purposes only, in real life code
//you shall avoid code like this here
System.out.println(std);
}
}
public TryArray(int lengthOfArray) { //Constructor for the length Array
arr = new Students[lengthOfArray];
}
}