有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java十进制输入,然后是二进制输入(不使用Integer.parseInt)

我是计算机科学一年级的学生。这个问题已经被问过很多次了,我也经历过这些。但我仍然无法在当前代码中找到需要修复的地方。我已经编写了将十进制转换为二进制的代码。以下是示例输入和输出

样本输入

4
101
1111
00110
111111

样本输出

5
15
6
63

我理解二进制转换的概念。但是,我无法为指定的数字输入二进制值,并且得到了不正确的输出。我不能使用整数。帕森特。 下面是从二进制到十进制的粗略转换练习

Binary to Decimal 
    1       0       1       0 -binary
    3       2       1       0 -power
    2       2       2       2 -base
    1*2^3 + 0*2^2 + 1*2^1 + 0*2^0
    8     + 0     + 2     + 0     = 10

代码

public class No2_VonNeumanLovesBinary {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int numTotal, binaryNum, decimalNum = 0, remainder;
        numTotal = s.nextInt();
        for(int i = 0 ; i <= numTotal; i++){
        // This is to get binaryNum input. However I am not getting the expected result.
            binaryNum = s.nextInt();
            while(binaryNum != 0){
                remainder = binaryNum % 10;
                decimalNum = decimalNum + (remainder * i);
                i = i * 2;
                binaryNum = binaryNum / 10;
            }
            System.out.println(decimalNum);
        }
    }
}

谢谢


共 (1) 个答案

  1. # 1 楼答案

    有两件事需要解决。在while循环中使用除i以外的变量。打印值后,将decimalNum重置为0。i、 e

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int numTotal, binaryNum, decimalNum = 0, remainder;
        numTotal = s.nextInt();
        for(int i = 0 ; i <= numTotal; i++){
            // This is to get binaryNum input. However I am not getting the expected result.
            binaryNum = s.nextInt();
            int j = 1;
            while(binaryNum != 0){
                remainder = binaryNum % 10;
                decimalNum = decimalNum + (remainder * j);
                j = j * 2;
                binaryNum = binaryNum / 10;
            }
            System.out.println(decimalNum);
            decimalNum = 0;
        }       
    }