Java 整数计数错误
我正在做一个大项目,但对于这个问题,我写了一个简单的例子。我有两门课Java 整数计数错误,java,member,static-members,Java,Member,Static Members,我正在做一个大项目,但对于这个问题,我写了一个简单的例子。我有两门课 public class Main { public static void main(String[] args) { CustomType[] customType = new CustomType[3]; for(int i = 0; i < 3; i++) { customType[i] = new CustomType(i
public class Main
{
public static void main(String[] args)
{
CustomType[] customType = new CustomType[3];
for(int i = 0; i < 3; i++)
{
customType[i] = new CustomType(i);
}
for(int i = 0; i < 3; i++)
{
System.out.println("Main " + customType[i].integer);
}
}
}
我得到以下输出:
CustomType: 0
CustomType: 1
CustomType: 2
Main 2
Main 2
Main 2
但我想得到这个:
CustomType: 0
CustomType: 1
CustomType: 2
Main: 0
Main: 1
Main: 2
static
是提示
为什么您认为一个静态变量首先会绑定到一个特定的实例
尝试使用public int-integer
而不是公共静态整数代码>并查看实例变量背后的魔力。您的问题是因为您正在使用静态变量作为整数
静态变量对于对象或类的所有实例都是通用的(在您的示例中是CustomType
class)。简单地说,创建静态变量的一个副本,并在类的所有实例之间共享
因此,当您在for
循环的索引0处创建CustomType
对象时,所有实例的静态变量值均为0。使用数组的索引位置1时,所有实例的索引位置都将更改为1。当您的for
循环在索引位置2结束时,static
变量结束时,所有实例的值均为2
相反,您需要做的是使用:
public int integer
这将为每个CustomType
对象提供其各自的integer
变量,该变量将被指定您要查找的正确值。如果您希望每个对象具有不同的值,则不要将变量设为静态,而是将其设置为private,并创建一个getter方法来检索您的私有var
这个
到
您的getter方法将检索数据
public int getInt()
{
return integer;
}
您误解了static
的含义。您可能希望integer
不是static
。谢谢您,我删除了该static关键字,我的项目没有问题:D
public static int integer;
private int integer;
public int getInt()
{
return integer;
}