2016-09-17 12 views
0

我在android studio中創建了一個應用程序,該應用程序將數字從基數10更改爲基數2.我創建了下面的算法,但我無法調用該類並獲取它以打印結果。 任何人都可以幫助我嗎?提前致謝。在Android Studio中調用一個類

這是我的代碼,

public class baseconv { 
    float m = Float.parseFloat(number.getText().toString()); 
    int n = (int) m; 
    int pow = 1; 
    int x = 0; 

    public void calculate() { 
     while (n > 0) { 
      x = x + (n % 2)*pow; 
      n = n/2; 
      pow = pow * 10; 
     } 
    } 

} 
+0

您有什麼問題? –

+0

什麼是「數字」 –

回答

0

要在基地10整數轉換基地2試試這個,

String baseTwoString = Integer.toString(your_integer, 2); 

但如果你是特別的,你需要使用閱讀您的自定義算法。

在你的活動,

String input = number.getText().toString(); 
try { 
    int n = (int) Float.parseFloat(input); 
    BaseConvert converter = new BaseConvert(); 
    int output = converter.calculate(n); 
    Log.e("output : ", output); 
} catch(NumberFormatException e) { 
    e.printStackTrace(); 
} 

你的轉換器類,

public class BaseConvert { 

    public int calculate (int n) { 
     int pow = 1; 
     int x = 0; 
     while (n > 0) { 
      x = x + (n % 2) * pow; 
      n = n/2; 
      pow = pow * 10; 
     } 
     return pow; 
    } 

} 
相關問題