计算机科学教授在我们的作业中给了我们一个问题...我不确定该如何继续下去,我写的代码似乎非常失败。以下是问题描述:
(二进制转十进制)编写一个递归方法,将二进制字符串解析为十进制整数。该方法的头部是:
public static String bin2Dec(String binaryString)
编写一个测试程序,提示用户输入一个二进制字符串,并显示其对应的十进制数。
非常感谢任何帮助。以下是我的代码:
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 "";
}
}
in
字符串的子字符串传递给bin2Dec
函数即可。也就是说,不需要使用index
。 - Scary Wombat