2

I am making a BCD class as an exercise for school, and am encountering some issues. Below is my BCD class.

My problem is with the multiplyBCDs method. It works fine with smaller numbers such as 4,329 * 4, however, with larger products, such as the product of 4,329 and 29,385, I receive a NullPointerException error at the first line of my addBCDs method:

int[] added = new int[other.numberOfDigits()];

I have tried retracing the problem and could not find the issue. Why am I receiving this error and how could I fix it?

Thanks for the help!

swallow
  • 23
  • 4
  • The code doesn't compile, you're missing multiplyBy and multiplyByTen. – Robert Bain Nov 05 '14 at 20:48
  • @RobertBain Sorry! forgot to include it--just edited it to include those two, it should work fine now – swallow Nov 05 '14 at 20:53
  • The following main method works for me. What am I missing? public static void main(String[] args) { BCD bcd = new BCD(new int[] { 4329, 29385 }); bcd.print(); } – Robert Bain Nov 05 '14 at 20:59
  • @RobertBain That just concatenates the two numbers— this is how I have it in my driver: BCD bcd = new BCD(4329); BCD bcd2 = new BCD(29385); BCD bcd3 = bcd.multiplyBCDs(bcd2); bcd3.print(); – swallow Nov 05 '14 at 21:09

2 Answers2

0
int[] added = new int[other.numberOfDigits()];

The only way you can get an NPE on that line is if other is null.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • That's what I thought, but I can't figure out why other would be null. The only thing I can think of is the `newBCD = newBCD.addBCDs(dig);` line, but newBCD is set to 0 so I think it should work... – swallow Nov 05 '14 at 21:35
  • Then you need to re-examine your assumptions, because it certainly is null. – user207421 Nov 05 '14 at 22:16
0

In the method:

public BCD multiplyBy(int num)

In the last else statement, the following condition is never met:

if (x == digits.length - 1 && carry != 0)

and so "ans" is never set and remains null.

Robert Bain
  • 9,113
  • 8
  • 44
  • 63
  • You're very welcome, glad it helped. Out of curiosity, what did you set it to when the condition wasn't met? – Robert Bain Nov 05 '14 at 22:53
  • I just made an else statement under that if statement that said `ans = new BCD(answer)` It's been working perfectly for all my tests so far – swallow Nov 05 '14 at 23:12