Mar*_*rio 21 java string integer user-input data-manipulation
所以基本上用户从扫描仪输入中输入一个序列.
12, 3, 4
等
它可以是任何长的长度并且它必须是整数.
我想将字符串输入转换为整数数组.
所以int[0]
会12
,int[1]
也会3
,等等
任何提示和想法?我正在考虑实现if charat(i) == ','
获取前一个数字并将它们解析在一起并将其应用于数组中当前可用的插槽.但我不太确定如何编码.
Jav*_*vil 34
你可以从扫描仪读取整个输入行,然后拆分行,,
然后你有一个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]);
}
Run Code Online (Sandbox Code Playgroud)
正如YoYo的回答所示,在Java 8中可以更简洁地实现上述目标:
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
Run Code Online (Sandbox Code Playgroud)
处理无效输入
在这种情况下,你需要考虑你想要做什么,你想知道那个元素有错误的输入或只是跳过它.
如果您不需要知道无效输入但只想继续解析数组,则可以执行以下操作:
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);
Run Code Online (Sandbox Code Playgroud)
我们应该修剪结果数组的原因是,结尾处的无效元素int[]
将由a表示0
,这些需要被删除以区分有效输入值0
.
结果是
输入:"2,5,6,坏,10"
输出:[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;
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,错误输入(不是有效整数)元素将为null.
结果是
输入:"2,5,6,坏,10"
输出:[2,3,6,null,10]
您可以通过不捕获异常来提高性能(有关此内容的更多信息,请参阅此问题)并使用不同的方法来检查有效的整数.
YoY*_*oYo 20
逐行
int [] v = Stream.of(line.split(",\\s+"))
.mapToInt(Integer::parseInt)
.toArray();
Run Code Online (Sandbox Code Playgroud)
Stream.of().mapToInt().toArray()
似乎是最好的选择。
int[] arr = Stream.of(new String[]{"1", "2", "3"})
.mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));
Run Code Online (Sandbox Code Playgroud)