2014-11-05 34 views
2

我正在为BCD做一个BCD课程,并遇到一些问题。以下是我的BCD课程。自制BCD类 - 乘法BCD错误

我的问题是multiplyBCDs方法。 它正常工作与更小的数字,如4329 * 4,然而,与较大的产品,如4329和29385的产品,我在addBCDs方法的第一行收到NullPointerException错误:

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

我试图回溯这个问题并且找不到问题。为什么我收到这个错误,我该如何解决?

感谢您的帮助!

+0

该代码不能编译,你错过了multiplyBy和multiplyByTen。 – 2014-11-05 20:48:00

+0

@RobertBain对不起!忘了包括它 - 只是编辑它包括这两个,现在应该工作正常 – swallow 2014-11-05 20:53:14

+0

以下主要方法适用于我。我错过了什么? \t public static void main(String [] args){ \t \t BCD bcd = new BCD(new int [] {4329,29385}); \t \t bcd.print(); \t} – 2014-11-05 20:59:28

回答

0

在该方法中:

public BCD multiplyBy(int num) 

在最后else语句,下面的条件,从来没有遇到过:

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

等 “ANS” 从未设置和保持为空。

+0

Ahh没有明白 - 像魅力一样工作!非常感谢! – swallow 2014-11-05 22:23:37

+0

非常欢迎,很高兴帮助。出于好奇,当条件没有得到满足时,你设定了什么? – 2014-11-05 22:53:32

+0

我刚刚做了一个else语句,该语句表示'ans = new BCD(answer)' 迄今为止我的所有测试都完美地工作 – swallow 2014-11-05 23:12:56

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

您可以在该行上获得NPE的唯一方法是如果other为空。

+0

这就是我的想法,但我不明白为什么其他将是空的。我只能想到的是\t \t \t'newBCD = newBCD.addBCDs(dig);' 行,但newBCD设置为0,所以我认为它应该工作... – swallow 2014-11-05 21:35:55

+0

然后,您需要重新检查您的假设,因为它肯定是空的。 – EJP 2014-11-05 22:16:14