为什么我的程序不返回二进制数?

时间:2016-02-20 18:16:20

标签: java

因此程序应该将二进制数转换为十进制数,首先检查它是否是二进制数然后转换。无论我给出什么输入,它总是说输入不是二进制数,我无法弄清楚为什么。这是我的代码。

public class Conversion {
    public static void main (String []args){
        String binaryNumber = args[0];
        if (checkBinary(binaryNumber)){
            int decimalNumber = binaryToDecimal(binaryNumber);
            System.out.print("The binary number " + binaryNumber + "is " + decimalNumber + "in base 10." );
        }
        else {
            System.out.println("The input is not binary!");
        }
    }

    public static boolean checkBinary(String binaryNumber){
        for (int i=0; i < binaryNumber.length(); i++) {
            char x = binaryNumber.charAt(i);
            if (x != '0' && x != '1'){
                return false;
            }
        }
        return true;
    }

    public static int binaryToDecimal(String binaryNumber) {
        int z = 1;
        int y = 0;
        for (int i = binaryNumber.length()- 1; i >= 0; i--){
            if (binaryNumber.charAt(i)=='1'){
                y += z;
            }
            z *= 2;
        }
        return y;
    }
}

2 个答案:

答案 0 :(得分:1)

你的班级有这个输出,这样就可以正常运行了 线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:0     在Conversion.main(Conversion.java:10) 为了避免这种问题,使用Scanne可以更好地解决问题,所以我只需要替换:

`String binaryNumber = args[0]; `

代表

`    

 Scanner input = new Scanner(System.in);
 System.out.println("Enter Binary: ");
  String binaryNumber = input.next();`   

 

整个代码如下并且运行良好(Java 8):

import java.util.Scanner;

public class Conversion {

    public static void main (String args[]){    
       // replace :String binaryNumber = args[0];
        Scanner input = new Scanner(System.in);
        System.out.println("Enter Binary: ");
        String binaryNumber = input.next();

        if (checkBinary(binaryNumber)){
            int decimalNumber = binaryToDecimal(binaryNumber);
            System.out.print("The binary number " + binaryNumber + " is " + decimalNumber + " in base 10." );
        }
        else {
            System.out.println("The input is not binary!");
        }
        input.close();
    }
    public static boolean checkBinary(String binaryNumber){
        for (int i=0; i = 0; i--){
            if (binaryNumber.charAt(i)=='1'){
                y += z;
            }
            z *= 2;
        }
        return y;
    }


}


 

输出: 输入二进制: 01000100111 二进制数0100​​0100111在基数10中为551。

答案 1 :(得分:1)

您只需将if (x != '0' && x != '1')修改为if (x != '0' || x != '1')

即可