Comp sci professor gave us this problem in our homework... I'm not sure how to proceed and the code I have written seems to be failing miserably. Here is the prompt:
(binary to decimal) Write a recursive method that parses a binary number as a string into a decimal integer. The method header is:
public static String bin2Dec(String binaryString)
write a test program that prompts the user to enter a binary string and displays its decimal equivalent.
Any help greatly appreciated. Here is my code as follows:
import java.util.Scanner;
public class HW04_P5 {
static int index = 0;
static int power = 0;
static int number = 0;
static boolean exit = false;
@SuppressWarnings("resource")
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print(" Enter a binary number to convert to decimal: ");
String in = scan.nextLine();
index = in.length()-1;
System.out.print(" Binary number converted to decimal: "+bin2Dec(in));
}
public static String bin2Dec(String in)
{
if((in.substring(index,index+1).equals("1"))&&(index>0))
{
number += Math.pow(2,power);
System.out.print(number);
power++;
index--;
bin2Dec(in);
}
else if((in.substring(index,index+1).equals("0"))&&(index>0))
{
power++;
index--;
bin2Dec(in);
}
System.out.print(number);
return "";
}
}
bin2Decthat is a substring of theinString. i.e. no need to haveindex