Martin
Martin

Reputation: 3

Constructor Bug

I am trying to make a class that represents an integer with 100 digits. Not so much because I need it, but to learn more about constructors. The constructor takes a String (all numbers) and places each digit into an element of an array. Index 0 is the ones place, Index 1 is the tens place, ... Whenever I try to create a second object (Bint), it replaces all the fields of the first Bint with the fields of the second Bint. (Bint = Big Int)

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)));
}

Prints out 46 (23 + 23, because b2 somehow replaces b1 in the constructor.)

Any help is appreciated, Thanks!

Upvotes: 0

Views: 136

Answers (1)

Kedar Parikh
Kedar Parikh

Reputation: 1271

static fields belong to class and are not specific to any object of the class.

suggested reading:http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

Upvotes: 2

Related Questions