簡體   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