繁体   English   中英

不使用 parseint 或 arrays 的二进制到十进制转换器

[英]binary to decimal converter without using parseint or arrays

使字符串索引超出范围,但我不明白为什么我经历了大约 50 次

import java.util.Scanner;
public class binary {

    public static void main(String[] args) {
        System.out.println("Enter the first binary number");
        Scanner keyboard = new Scanner(System.in);
        String num1 = keyboard.next();
        //System.out.println("Enter the second binary number");
        //String num2 = keyboard.next();
        
        int total = 0;
        for(int i = num1.length(); i>0;i--) {
            if(num1.charAt(i) == 1) {
                total += 2*i;
            }
            
        }
        if(num1.charAt(3) == 1) {
            total -= 1;
        }
        System.out.println(total);

    }

}

这是您尝试做的事情的完整解决方案,包括一组测试:

class binary {

    private static int binaryToInt(String binary) {
        int total = 0;
        for (int i = 0 ; i < binary.length(); i++) {
            total *= 2;
            if (binary.charAt(i) == '1')
                total += 1;
        }
        return total;
    }

    private static void test(String binary, int expected) {
        int n = binaryToInt(binary);
        String rightWrong = "right";
        if (n != expected) {
            rightWrong = String.format("WRONG! (should be %d)", expected);
        System.out.printf("%s -> %d is %s\n", binary, n, rightWrong);
    }

    public static void main(String[] args) {
        test("0", 0);
        test("1", 1);
        test("10", 2);
        test("100", 4);
        test("111", 7);
        test("0000111", 7);
        test("1010101010", 682);
        test("1111111111", 1023);

        System.out.println("");

        // test sanity check
        System.out.println("This last test should fail (we are just testing the test method itself here)...");
        test("1010101010", 0);
    }
}

结果:

0 -> 0 is right
1 -> 1 is right
10 -> 2 is right
100 -> 4 is right
111 -> 7 is right
0000111 -> 7 is right
1010101010 -> 682 is right
1111111111 -> 1023 is right

This last test should fail (we are just testing the test method itself here)...
1010101010 -> 682 is WRONG! (should be 0)

您的代码中的一个重要问题尚未在评论或早期答案中得到解决。 请注意这一行与代码中的行:

if (binary.charAt(i) == '1')

您正在测试数值1 ,这永远不会是true ,因为您从charAt()取回一个字符,而不是一个数字。

虽然length()计算元素的数量,但它们的索引从 0 开始。对于“1111”字符串,最后一个字符的索引为 3,而不是 4,因此.length()-1 您需要将 for 语句更改为for(int i = num1.length()-1; i>=0;i--) (还要注意条件更改)或将 charAt 语句更改为if(num1.charAt(i-1) == '1')

另外,根据您要执行的操作,我假设对于total += 2*i您实际上需要像total += Math.pow(2, i-length())类的东西,具体取决于您首先决定对i做什么.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM