java如何使我的二进制到十进制转换程序也读取0s?
这个程序应该将二进制数转换为十进制数,并在输入有非二进制数时抛出异常。这个程序将读取1s,但当我输入0s时,它将抛出异常并告诉我它不是二进制的
测试程序:
//Prepare scanner from utility for input.
import java.util.Scanner;
public class Bin2Dec {
public static void main (String[] args){
//Convert the input string to their decimal equivalent.
//Open scanner for input.
Scanner input = new Scanner(System.in);
//Declare variable s.
String s;
//Prompt user to enter binary string of 0s and 1s.
System.out.print("Enter a binary string of 0s and 1s: ");
//Save input to s variable.
s = input.nextLine();
//With the input, use try-catch blocks.
//Print statement if input is valid with the conversion.
try {
System.out.println("The decimal value of the binary number "+ "'" + s + "'" +" is "+conversion(s));
//Catch the exception if input is invalid.
} catch (BinaryFormatException e) {
//If invalid, print the error message from BinaryFormatException.
System.out.println(e.getMessage());
}
}
//Declare exception.
public static int conversion(String parameter) throws BinaryFormatException {
int digit = 0;
for (int i = parameter.length(); i > 0; i--) {
char wrong_number = parameter.charAt(i - 1);
if (wrong_number == '1') digit += Math.pow(2, parameter.length() - i);
//Make an else statement and throw an exception.
else if (wrong_number == '0') digit += Math.pow(2, parameter.length() - i);
else
throw new BinaryFormatException("");
}
return digit;
}
}
# 1 楼答案
由于以下几行原因,此程序只接受“1”作为字符:
由于不存在
if(wrong_number == '0')
,该数字将只接受1,并在遇到0时抛出异常除此之外: 尽可能避免
Math.pow
。因为它是相当资源密集型的,在这种情况下完全没有用。2^x可以通过位移位更容易地生成:最后:java已经为此提供了method:
# 2 楼答案
问题在于你的逻辑。由于您处理的是二进制数('1'和'0'),但您只检查了1,所以您也应该检查'0',并且只有当它不是'0'和'1'时才会抛出异常