gpt4 book ai didi

java - 将字符串数组转换为整数数组

转载 作者:IT老高 更新时间:2023-10-28 20:49:47 26 4
gpt4 key购买 nike

所以基本上用户从扫描仪输入输入序列。12、3、4
它可以是任意长度,并且必须是整数。
我想将字符串输入转换为整数数组。
所以 int[0] 会是 12int[1] 会是 3 等等。

有什么建议和想法吗?我正在考虑实现 if charat(i) == ',' 获取先前的数字并将它们一起解析并将其应用于数组中的当前可用插槽。但我不太确定如何编写代码。

最佳答案

你可以从扫描仪读取整个输入行,然后用 分割行,然后你有一个 String[],将每个数字解析为 int[ ] 索引一对一匹配...(假设输入有效且没有 NumberFormatExceptions)类似

String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch
// and another index for the numbers if to continue adding the others (see below)
numbers[i] = Integer.parseInt(numberStrs[i]);
}

作为 YoYo's answer建议,以上可以在 Java 8 中更简洁地实现:

int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();  

处理无效输入

你需要考虑在这种情况下你需要做什么,你想知道那个元素有错误的输入还是直接跳过它。

如果您不需要了解无效输入但只想继续解析数组,您可以执行以下操作:

int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[index] = Integer.parseInt(numberStrs[i]);
index++;
}
catch (NumberFormatException nfe)
{
//Do nothing or you could print error if you want
}
}
// Now there will be a number of 'invalid' elements
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);

我们应该修剪结果数组的原因是 int[] 末尾的无效元素将由 0 表示,这些需要删除为了区分 0 的有效输入值。

结果

Input: "2,5,6,bad,10"
Output: [2,3,6,10]

如果您以后需要了解无效输入,您可以执行以下操作:

Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[i] = Integer.parseInt(numberStrs[i]);
}
catch (NumberFormatException nfe)
{
numbers[i] = null;
}
}

在这种情况下,错误的输入(不是有效的整数)元素将为空。

结果

Input: "2,5,6,bad,10"
Output: [2,3,6,null,10]


您可以通过不捕获异常 (see this question for more on this) 并使用不同的方法检查有效整数来潜在地提高性能。

关于java - 将字符串数组转换为整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18838781/

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