2017-10-09 40 views
0

我正在寫一個程序,我想遍歷一個文檔中的某些屬性,看起來像這樣的ID:如何從涉及其他字符的字符串中獲取int?

"id": "competitor:2672" 

我想根據我從一個excel文件中讀取的數據進行迭代。唯一的問題是,在所述excel文件中,ID僅以「競爭者ID」列給出爲

2672 

我無法將給定的字符串解析爲整數。什麼是比較兩個ID

使用Apache POI的最好和最乾淨的方式,我想這樣做

String COLUMN_ID = "G" // Column letter in which the IDs are stored 
Document home = competitors.get(0); 
Document away = competitors.get(1); 
String homeIDString = home.get("id").toString(); 
int homeID = //how to get this from the upper string? 
String awayIDString = away.get("id").toString(); 
int awayID = //how to get this from the upper string? 
XSSFWorkbook workbook = new XSSFWorkbook(inputStream); 
XSSFSheet sheet = workbook.getSheetAt(0); 
for (int row=0; <something>; row++) { 
    XSSFCell cell = sheet.getRow(row).getCell(CellReference.convertColStringToIndex(COLUMN_ID)); 
    if (cell.getCellTypeEnum().equals(NUMERIC)) int cellValue = (int) cell.getNumericValue(); 
    if (cellValue == homeID) { do something } 
    else if (cellValue == awayID) { do something } 
} 
+1

之前使用子只刪除competitor:「*我無法分析給定的字符串到整數*。」 - 爲什麼不呢?我想你可以檢查id字符串是否以excel中的數字結尾,但我不明白是什麼阻止了你從字符串中提取數字並將其作爲數字進行比較。 – azurefrog

+0

我在編程方面不是很有經驗,但據我的經驗,這會給我一個** NumberFormatException **。或者我錯了? –

回答

3

目前你得到一個NumberFormatException因爲你想你的String轉換成int然後再與另一個int比較。

@azurefrog說的是,你可以嘗試,而不是你的int轉換爲String(反過來),它會沒事的。

strVariable.endsWith(String.valueOf(intVariable))

然而,這具有"id": "competitor:2672"72將返回true太多的問題。


一個更好的辦法是將2672爲int

String myInput = "competitor:2672";  // "competitor:2672" 
myInput = myInput.substring(11);   // "2672" 
int myValue = Integer.parseInt(myInput); // 2672 
相關問題