2015-02-06 117 views
8

如何使用方法int converter(int num)將基數10數轉換爲基數3數。將基數10轉換爲基數3數

import java.util.Scanner; 

public class BaseConverter { 
    int answer; 
    int cvt = 0; 
    while (num >= 0) { 
     int i = num/3; 
     int j = num % 3; 
     String strj = Integer.toString(j); 
     String strcvt = Integer.toString(cvt); 
     strcvt = strj + strcvt; 
     num = i; 
     break; 
    } 
    answer = Integer.parseInt("strcvt"); 
    return answer; 
} 

public static void main(String[] agrs) { 
    Scanner in = new Scanner(System.in); 
    System.out.println("Enter a number: "); 
    int number = in.nextInt(); 
    System.out.print(converter(number)); 
    in.close(); 
} 

這是編譯完成。但是,當我試圖運行它,並輸入一個數字時,它顯示 java.lang.NumberFormatException:對於輸入字符串:「strcvt」 我不知道如何解決它。我怎樣才能不使用字符串?

+0

你是不是想在'parseInt'方法中使用變量'strcvt'?您的代碼當前通過字符串「strcvt」 – 2015-02-06 08:45:33

+0

您對此行的期望是什麼? 'Integer.parseInt(「strcvt」);' – 2015-02-06 08:45:49

+0

我在一團糟@^@ – AliceBobCatherineDough 2015-02-06 09:06:09

回答

7

根本不需要使用字符串。

嘗試此代替

public static long asBase3(int num) { 
    long ret = 0, factor = 1; 
    while (num > 0) { 
     ret += num % 3 * factor; 
     num /= 3; 
     factor *= 10; 
    } 
    return ret; 
} 

注:在計算機中的數字是隻有永遠N位即32位或64位即它們是二進制的。但是,您可以執行的操作是創建一個數字,以10爲底數打印時,實際上將顯示爲基數3中的數字。

+0

非常感謝你! – AliceBobCatherineDough 2015-02-06 09:03:37

+1

@PeterLawrey,'asBase3(3);'打印「1」而不是「10」。 – 2015-10-10 17:39:37

+0

@SedatPolat我糾正了這一點。 – 2015-10-11 10:32:58

3

不使用變量聲明String strcvt,而是由於錯字錯你作爲"strcvt"

變化

answer = Integer.parseInt("strcvt"); 

answer = Integer.parseInt(strcvt); 
1

你要解析的strcvt值不是字符串「strcvt」

因此,您必須刪除雙重線條answer = Integer.parseInt(strcvt); 並在循環外定義變量strcvt。 將代碼更改爲:

public static int converter(int num) { 
    int answer; 
    int cvt = 0; 
    String strcvt = null ; 
    while (num >= 0) { 
     int i = num/3; 
     int j = num % 3; 
     String strj = Integer.toString(j); 
     strcvt = Integer.toString(cvt); 
     strcvt = strj + strcvt; 
     num = i; 
     break; 
    } 
    answer = Integer.parseInt(strcvt); 
    return answer; 
} 
+0

謝謝!有用!但我得到的答案是錯誤的。我必須檢查我的邏輯。 – AliceBobCatherineDough 2015-02-06 09:04:56

相關問題