我正在尝试创建一个表示 100 位整数的类。与其说是因为我需要它,不如说是为了了解更多关于构造函数的知识。构造函数接受一个字符串(所有数字)并将每个数字放入数组的一个元素中。索引 0 是个位,索引 1 是十位,...每当我尝试创建第二个对象(Bint)时,它都会用第二个 Bint 的字段替换第一个 Bint 的所有字段。 (宾特=大整型)
public class Bint
{
// Fields:
private static int[] nums = new int[100];
// Constructor:
public Bint(String s)
{
for(int i = 0; i < s.length(); i++)
{
nums[i] = Integer.parseInt("" + s.charAt(s.length() - i - 1));
}
}
...
public static void main(String[] args)
{
Bint b1 = new Bint("12");
Bint b2 = new Bint("23");
System.out.println(toString(add(b1, b2)));
}
打印出 46(23 + 23,因为 b2 在构造函数中以某种方式替换了 b1。)
感谢任何帮助,谢谢!
最佳答案
static
字段属于类,并不特定于该类的任何对象。
建议阅读:http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
关于java - 构造函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28757134/