java - 如何让我的二进制到十进制转换程序也读取 0?

标签 java exception binary decimal

该程序应该将二进制数转换为十进制数,并在输入有非二进制数时抛出异常。这个程序会读取1,但是当我输入0时,它会抛出异常并告诉我它不是二进制。

测试程序:

//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”作为字符:

if (wrong_number == '1') digit += Math.pow(2, parameter.length() - i);
          //Make an else statement and throw an exception.
else 
    throw new BinaryFormatException("");

由于没有if(wrong_number == '0'),所以数字只会接受1,遇到0就会抛出异常。

除此之外: 如果可能的话,以任何方式避免使用 Math.pow。因为它非常消耗资源,并且在这种情况下完全没有用。使用位移位可以更容易地生成 2^x:

int pow_2_x = (1 << x);

最后:java已经提供了method为此:

int dec = Integer.parseInt(input_string , 2);

关于java - 如何让我的二进制到十进制转换程序也读取 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32809115/

相关文章:

java - Eclipse插件: Custom plugin. xml类编辑器

java - 如何编写多线程单元测试?

java - 我的 java zkoss 程序出了什么问题

Java:对所有捕获的异常调用方法

java: bind exception address in use 未使用时报错(netstat显示)

c++ - 如何在 Visual Studio 2008 C++ 中捕获被零除错误?

java - 二进制除法问题 : bad examples on internet or what am I missing?

java - JDBC 在我的 postgres 查询中将表大写

c# - 以编程方式将 XLS 转换为 XLSB?

java - HttpURLConnection 的意外结果 - 读取远程二进制文件