2014-02-23 57 views
0

我想從包含數字(有些是2位數字)的字符串中填充一個字節數組,其中包含空格。我知道有一個parseByte函數,但我不確定如何在填充數組時使用它,因爲它似乎只是將字符串作爲一個整數。從字符串填充數組字節

我不-工作代碼:

public static void popArray(byte[][] array, String numbers) 
{ 
    int counter = 0;  //counter to track position in string of data 
    for(int i=0; i<20; i++)   //cycle rows 
    { 
     for(int y=0; y<20; y++) //cycle columns 
     { 
     array[i][y] = (byte)(Character.digit(.charAt(counter), 10));  
     counter++; //increase place in data string         
     } 
    } 
} 
+0

u能解釋如果輸入是ABCDEF ...然後什麼將是關於索引 – Kick

+0

的字節值的數組將會是這樣的8 78 90 79 4 2 23 3 ...等 –

+0

你使用二維數組,所以會是[0] [0],[0] [ 1] ...值 – Kick

回答

0

分割字符串的空間,然後遍歷結果數組了:

String[] parts = numbers.split("\\s+"); 
int counter = 0;     //counter to track position in string of data 
for (int i = 0; i < 20; i++) {  //cycle rows 
    for (int y = 0; y < 20; y++) { //cycle columns 
     String s = parts[counter]; 
     byte b = (byte)(Integer.parseInt()) 
     array[i][y] = b;  
     counter++; //increase place in data string         
    } 
} 
+0

這給了我一個數組越界異常。爲了澄清,'String [] arr = numbers.split(「\\ s +」);'填充數組arr,其中每個元素都是我輸入的數字? –

+0

是的。數字是否包含少於20x20(= 400)的數字?我已經更改了代碼,讓每個數組都可以在不同的行上訪問,因此更容易進行調試。 –

+0

原始數據肯定是20 x 20,但我有點擔心要通過它們來檢查字符串中的所有數據。通過限制程序只填充前100個元素,它巧妙地設法吐出我正在尋找的答案。 –