![](/img/trans.png)
[英]Get a value of a variable of a class instance while being at another class instance
[英]assigning value of one class's instance variable in another class
我正在尝试在文件 class 中分配 FileData 实例变量的值
起初 FileData 的 nextIndex 应该都是-1,然后它应该被分配计数器的值我试过 get、set 和 FileData 数组来赋值但是它不起作用并给出 NULL POINTER EXCEPTION我试过:
class FileData
{
int nextIndex = 0;
public void setIndex()
{
for(int i=0; i<10;i++)
{
nextIndex = -1;
}
}
}
class File
{
public static void main(String args[])
{
FileData[] FD = new FileData[10];
for(int i=0; i<5;i++)
{
FD[i].nextIndex = i;
}
}
}
使用对象时,首先必须创建一个实例。 我所做的只是在循环中添加一个声明符并格式化代码:
class FileData {
int nextIndex = 0;
public void setIndex() {
for (int i = 0; i < 10; i++) {
nextIndex = -1;
}
}
}
class File {
public static void main(String args[]) {
FileData[] FD = new FileData[10];
for (int i = 0; i < 5; i++) {
FD[i] = new FileData();
FD[i].nextIndex = i;
}
}
}
注意FileData[] FD = new FileData[10];
bit 只是声明了一个 FileData 类型的数组,还没有给每个 object 其需要的存储空间。
这里的数组元素是null:
FileData[] FD = new FileData[10];
首先你需要创建对象:
for(int i=0; i < FD.length ;i++)
{
FD[i] = new FileData();
FD[i].nextIndex = i;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.