I wrote a program which, at first, was giving correct answers however I later wrote another method which caused my program to start failing. After that I deleted the second method but nothing seems to work to fix it. Can you guys tell me what the problem is?
Note: Method isNumeric just checks if the input String contains a non-numeric character.
For example: a number in octal basis "115" needs to be converted to decimal, meaning
(115)8 -> (?)10
The following formula gives us this:
115 = (1 × 8²) + (1 × 8¹) + (5 × 8⁰) = 77
This is the formula that the code is supposed to follow. Therefore the result of the conversion of 115 in octal basis to decimal is 77.
Another limitation of this is that this must use recursion.
It worked in the sense that it gave the correct result 5 times in a row for different String number inputs but something along the way changed and now gives wrong results.
public static int octalStringToDecimal(String numString) {
//Base case the numeric value is just 0 or where String is empty
if ((numString.equals(""))) {
return -9999;
}
//the String does not contain numeric characters
if((!isNumeric(numString))){
return -9999;
}
int rem, sum = 0, i = 0, basis = 8;
int number = Integer.parseInt(numString); //this is n
//while our number is not 0 then we keep on parsing
while (number != 0) {
rem = number % 10;
number = number / 10;
sum = rem * ((int) Math.pow(basis, i)) + octalStringToDecimal(String.valueOf(number));
i++;
}
//when out number is equal to 0 then we return the value
return sum;
}
public static boolean isNumeric(String string) {
try {
Integer.parseInt(string);
return true;
} catch (NumberFormatException e) {
return false;
}
}