我运行程序时遇到这些错误,有人能发现错误吗?我没有使用递归的经验,我可能搞乱了基本情况。我的测试由两个相同长度的数字组成,我的目标是在不使用内置类的情况下将两个Big数相乘。方法add只接受两个字符串,这些字符串是数字并添加它们,我检查了它,无论数字有多大,它都可以工作。
错误NumberFormatException:对于输入字符串:"" 的Integer.parseInt(Integer.java:592)
public static String mu (String value1, String value2){
int length1 = value1.length();
int length2 = value2.length();
//If one value has more digits than the other, add zeroes to the front...
int temp1;
int temp2;
int multiply;
if (length1==1 || length2 ==1){
temp1 = Integer.parseInt(value1);
temp2 = Integer.parseInt(value2);
multiply = temp1*temp2;
return multiply +"" ;
}else if (length1 ==0 || length2 ==0){
return "";
}
int firstHalf = length1/2;
int secondHalf = length1 - firstHalf;
String value1First = value1.substring(0, firstHalf);
String value1Second = value1.substring(firstHalf, secondHalf);
String value2First = value2.substring(0, firstHalf);
String value2Second = value2.substring(firstHalf, secondHalf);
String ac = mu (value1First, value2First);
String ad = mu (value1First, value2Second);
String bc = mu(value1Second, value2First);
String bd = mu(value1Second, value2Second);
String zeroesToAdd= null;
String zeroesToAdd2 = null;
for (int i=0; i<length1; i++){
zeroesToAdd = "0"+ zeroesToAdd;
}
for (int i=0; i<length1/2; i++){
zeroesToAdd2 = "0"+ zeroesToAdd2;
}
String firstPart = ac + zeroesToAdd;
String secondPart = (add(ad,bc))+zeroesToAdd2;
String thirdPart = bd;
String add1 = add(firstPart, secondPart);
String add2;
return add(add1, thirdPart);
}
答案 0 :(得分:2)
错误NumberFormatException:对于输入字符串:&#34;&#34; 的Integer.parseInt(Integer.java:592)
是由代码
引起的Integer.parseInt(value1) or
Integer.parseInt(value2)
您可能想尝试为str长度(1,1)(1,0)(0,1)(0,0)的组合添加更多个案。以下代码可能有所帮助!
if (length1==1 && length2 ==1){
temp1 = Integer.parseInt(value1);
temp2 = Integer.parseInt(value2);
multiply = temp1*temp2;
return multiply +"" ;
}else if (length1 ==0 && length2 ==0){
return "";
}
else if (length1 ==0 && length2 ==1){
return value2;
}
else if (length1 ==1 && length2 ==0){
return value1;
}
希望它有所帮助!