我试图理解数组对象,我想做的是在我拥有的每个类中调用我的数组。
这是我的代码:
projectProva.java
public class ProjecteProva {
Scanner sc = new Scanner(System.in);
private final int maxContador = 4;
private final DadeArr LlistaUsuari[] = new DadeArr[maxContador];
int ContadorActual;
}
DadeArr.java
public class DadeArr {
private String nomUsuari;
private String cognomUsuari;
public DadeArr(String nU, String nC){
nomUsuari = nU;
cognomUsuari = nC;
}
现在我正在projectProva.java中工作,我有一些方法可以将使用扫描仪输入的数据保存到数组中。
这是我的方法之一的示例:
public int inserir(int aContadorActual){
ContadorActual = 1;
for (int i=1;i<=ContadorActual;++i){
System.out.println("Introdueix el nom del usuari: ");
String nU = sc.nextLine();
//sd.setNomUsuari(Name);
System.out.println("Introdueix el teu cognom : ");
String nI = sc.nextLine();
LlistaUsuari[ContadorActual] = new DadeArr(nU,nI);
System.out.println("El teu usuari s'ha creat satisfactoriament");
}
ContadorActual++;
return ContadorActual;
}
此方法询问用户的姓名并将其保存在数组 LlistaUsuari 中。
然后,我想在同一包中的另一个 .java 文件中使用这个数组(包含数据),但我不知道如何正确调用该数组。
我刚刚开始学习这种类型的数组,我想了解它。
解决这个问题后,我期待获取所有数组信息并将其发送到数据库或文本文件。
如果我无法继续,我将切换到 Array 2D。
另外,我想知道这种类型的数组(数组对象)是否非常有用。
谢谢。 我也在https://www.reddit.com/r/javahelp/comments/dsyu4b/array_object/提出了这个问题?
最佳答案
您的代码中有多个陷阱。
1.您应该始终从索引 0 开始迭代数组(除非您有特殊需求或者您使用 Python 等数组从 0 开始的语言进行编程)
2. 应将循环中的条件设置为小于数组的确切长度。所以在你的情况下它将是 i < LlistaUsuari.length
。您得到的是 null,因为您只填充了数组的索引 #1。
您所需要的只是一个public
getter
您要访问的数组的方法。
类似于:
public DadeArr[] getLlistaUsuari() {
return this.LlistaUsuari;
}
这样就可以了。
在其他类中,创建 ProjecteProva
的实例(我们称之为 pPI
)并获取数组,只需执行 pPI.getLlistaUsuari()
即可。你就会拥有它,
关于java - 理解数组对象,我想做的是在我拥有的每个类中调用我的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58753677/