1

In Java, I have to make a constructor of an array in which each digit of a big number will be a different char of this array.

This is the main class:

 public static void main(String[] args) {
    BigNumber bn1 = new BigNumber(1500);
    BigNumber bn2 = new BigNumber("987349837937497938943242");  

    System.out.println("line 1: " + bn1);
    System.out.println("line 2: " + bn2);
}

I tried to make a constructor using a String but I'm not sure if it's good:

private String number;
private char[] n = null;

public BigNumber(String _number){
    number = _number;
    n = new char[number.length()];

    for (int i = 0; i < n.length; i++){
        n[i] = number.charAt(i);
    }
}

Or maybe there's a different way to do this?

Brent Worden
  • 10,624
  • 7
  • 52
  • 57

2 Answers2

1

"I have to make a constructor of an array in which each digit of a big number will be a different char of this array."

You can just do

n = _number.toCharArray();

which returns a character array of the String

private char[] n = null;

public BigNumber(String _number){
    n = _number.toCharArray();
}

If you want to print the BigNumber object as a String, you need to @Override the toString() method in the BigNumber class

public class BigNumber {
    ....

    @Override
    public String toString(){
        return Arrays.toString(n);
    }
}

The way you're currently printing won't print the array as you would expect. You need to override the toString() method to output the object as a String representation with your desired output format. My simple example just prints out the array as a String, though you can choose to format it any way you like. But keep in mind the method must return a String

Then you can do this

BigNumber bn2 = new BigNumber("987349837937497938943242");  
System.out.println("line 1: " + bn2);

Also NOTE : You cannot do this

BigNumber bn1 = new BigNumber(1500);

as the BigNumber constructor only take a String argument, where 1500 is an int. You could do this

BigNumber bn1 = new BigNumber(String.valueOf(1500));

UPDATE

If you wanted to accept an int as an argument to the constructor, you would need to create a separate constructor that takes an int argument. In which case you would also need to make the int a String, then get the character array. So you would have two constructors, one that takes a String and one that takes an int

public BigNumber(int number){
    String numString = String.valueOf(number);
    n = number.toCharArray();
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
0

String has a toCharArray() method that will give you what you want.

n = _number.toCharArray();

Of note, toCharArray returns a copy of the original string. So, any changes you make to the array will not be reflected in the source string.

Brent Worden
  • 10,624
  • 7
  • 52
  • 57