急...java程式:將二進位轉為十進位

Write an application that inputs an interger containing only 0s and 1s(i.e.,a binary interger)and prints its decimal equivalent

2 個解答

評分
  • anye
    Lv 5
    1 0 年前
    最佳解答

    請使用Integer Class下面的public static int parseInt(String s,

    int radix)

    throws NumberFormatExceptionParses the string argument as a signed integer in the radix specified by the second argument. The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned. An exception of type NumberFormatException is thrown if any of the following situations occurs: The first argument is null or is a string of length zero. The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX. Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1. The value represented by the string is not a value of type int. Examples: parseInt("0", 10) returns 0

    parseInt("473", 10) returns 473

    parseInt("-0", 10) returns 0

    parseInt("-FF", 16) returns -255

    parseInt("1100110", 2) returns 102

    parseInt("2147483647", 10) returns 2147483647

    parseInt("-2147483648", 10) returns -2147483648

    parseInt("2147483648", 10) throws a NumberFormatException

    parseInt("99", 8) throws a NumberFormatException

    parseInt("Kona", 10) throws a NumberFormatException

    parseInt("Kona", 27) returns 411787

    Parameters: s - the String containing the integer representation to be parsed radix - the radix to be used while parsing s. Returns: the integer represented by the string argument in the specified radix. Throws: NumberFormatException - if the String does not contain a parsable int.例:String binary="1010";System.out.println("Decimal="+Integer.parseInt(binary,2));接下來你應該知道怎麼寫了吧!只要再加上輸入的部份這個程式就完成了!

    參考資料: JavaTM 2 Platform Standard Edition 5.0
  • 1 0 年前

    我照我的想法寫過一次

    程式碼跟測試結果都放在這裡

    http://blog.yam.com/tony77794/article/6880776

    參考看看吧 ~

還有問題?馬上發問,尋求解答。