gpt4 book ai didi

java - 如何从包含其他字符的字符串中获取int?

转载 作者:行者123 更新时间:2023-12-01 20:11:15 25 4
gpt4 key购买 nike

我正在编写一个程序,我想使用如下所示的 ID 迭代文档中的某些属性:

"id": "competitor:2672"

我想根据从 Excel 文件中读取的数据进行迭代。唯一的问题是,在所述 Excel 文件中,ID 仅给出为

2672

在“竞争对手 ID”列中。

我无法将给定的字符串解析为整数。比较两个 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 }
}

最佳答案

您当前收到 NumberFormatException,因为您在与另一个 int 进行比较之前尝试将 String 转换为 int .

@azurefrog 的意思是,您可以尝试将 int 转换为 String(反之亦然),这样就可以了。

strVariable.endsWith(String.valueOf(intVariable))

但是,这存在一个问题,即 "id": "competitor:2672"72 也会返回 true

<小时/>

更好的方法是在将 2672 转换为 int 之前使用子字符串删除 competitor:

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

关于java - 如何从包含其他字符的字符串中获取int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46651165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com