2015-04-14 48 views
0

我想將一個字符串轉換爲一個整數,但我接受了一個錯誤。這裏是我的代碼:字符串到int parseInt

int foo = Integer.parseInt(ABoard[first]); 

if (computerBoard[foo] != -1) { 
    second = computerBoard[foo]; 
} else { 
    second = board.getRandomPosition(); 
    while (first==second) { 
     second = board.getRandomPosition(); 
    } 
} 

我想借此從一個字符串數組一個數字(INT),然後從一個int數組藉此數的值,如果這個數的值不爲-1。

+5

任何編程語言的錯誤都是有意義的信息。所以閱讀它,瞭解它,並在尋求幫助時至少*發佈實際錯誤* – Kon

+0

你得到的錯誤是什麼? –

+0

stacktrace會有幫助。 – Paul

回答

0

爲了解析Stringint您需要從中刪除所有非數字字符(假設我們對負整數不感興趣)。

下面是代碼這樣做:

int foo = Integer.parseInt(ABoard[first].replaceAll("[^0-9]", "")); 
1

您需要修剪掉所有的空格,你解析之前,

int foo = Integer.parseInt(ABoard[first].trim()); 

或更換所有非數字組成

int foo = Integer.parseInt(ABoard[first].replaceAll("[^0-9\\-]", ""); //including 0-9 and -