2016-02-08 32 views
0

我很難嘗試爲使用數組列表的這個示例構造一個構造函數。無法從字符串中獲取每個字符並將其添加到整數的ArrayList sn:知道bigInteger

public class BigIntConstructorDemo { 
public static void main(String[] args) { 


    BigInt1 b1 = new BigInt1("1000000"); 

    System.out.println("b1 is " + b1); 

    } 
} 

這是一個帶有數字的數組,該數組保存最多40位數。構造函數循環遍歷數組....

public class BigInt1 { 
public static final int MAX_DIGITS = 40; 
private int [ ] digits = new int[MAX_DIGITS]; 

public BigInt1(String s){ 
    for (int i = 0; i < MAX_DIGITS; i++) 
     digits [i] = 0; 
    int i = 0; 
    for(int j = s.length()-1; j >= 0; j--){ 
     digits[i] = s.charAt(j) - '0'; 
     i++;  
    } 
    } 
} 

然後使用toString方法。

public String toString(){ 
    String s = ""; 


    for (i = 0; i < MAX_DIGITS;i++) 

     s = digits[i] + s; 


    if (s.equals("")) 
     s = "0"; 
    return s; 

我知道我必須使用for循環,但我似乎無法得到正確的語法。我應該使用數組列表類中的.add方法嗎?怎麼可能在一個字符串中取一個字符,然後把它放到數組列表的每個元素中呢?

+1

Side-question:你知道[BigInteger](https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html)Java API類嗎?可能不想在這裏重新發明輪子。 – Mena

+0

是的,我知道,並不想重新發明輪子,但是爲了更好地理解我想嘗試創建我自己的,如果那對你很好。 – TyroProgrammer

+0

哈哈,這完全「我可以」,只是在這裏檢查健康狀況:) – Mena

回答

0

是的,使用add。

這是你的舊代碼的數組:

for(int j = s.length()-1; j >= 0; j--){ 
     digits[i] = s.charAt(j) - '0'; 
     i++;  
    } 

與ArrayList中的foreach你:

for (char c: s.toCharArray()) { 
    digits.add(c - '0'); 
} 

注意,字節順序(從左至右或從右至左)在切換這種情況下,如果你想以其他方式簡單循環,就像在你上一個例子中通過s.toCharArray()位置循環一樣:

char[] chars = s.toCharArray(); 
for(int j = chars.length-1; j >= 0; j--){ 
     digits.add(chars[j] - '0'); 
    } 
相關問題