将字符串数组转换为整数数组 [英] Converting String Array to an Integer Array

查看:158
本文介绍了将字符串数组转换为整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上用户从扫描仪输入中输入一个序列。
12,3,4 等等。

它可以是任何长度,并且必须是整数。

我想将字符串输入转换为整数数组。

所以 int [0] 12 int [1] 3 等。



任何提示和想法?我正在考虑实现如果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 ++)
{
//注意这是假设有效输入
//如果你想检查那么如果要继续添加其他数据,请添加一个try / catch
//以及数字的另一个索引(见下文)
numbers [i] = Integer.parseInt(numberStrs [i]);
}






as YoYo的回答表明,上述内容可以在Java 8中更加简洁地实现:

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






处理无效输入



在这种情况下你需要考虑你想要做什么,你想知道那个元素有错误的输入或者只是跳过它。 / p>

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

  int index = 0; 
for(int i = 0; i< numberStrs.length; i ++)
{
try
{
numbers [index] = Integer.parseInt(numberStrs [一世]);
index ++;
}
catch(NumberFormatException nfe)
{
//如果你想要
,你可以打印错误}
}
/ /现在会有一些'无效'元素
//最后需要修剪
numbers = Arrays.copyOf(numbers,index);

我们应该修剪结果数组的原因是<$ c末尾的无效元素$ c> int [] 将由 0 表示,需要删除这些以区分<$ c的有效输入值c $ c> 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 [一世]);
}
catch(NumberFormatException nfe)
{
numbers [i] = null;
}
}

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



结果


输入:2, 5,6,差,10

输出:[2,3,6,null,10]







您可以通过不捕获异常来提高性能(请参阅此问题以获取更多信息)并使用其他方法检查有效整数。


so basically user enters a sequence from an scanner input. 12, 3, 4, etc.
It can be of any length long and it has to be integers.
I want to convert the string input to an integer array.
so int[0] would be 12, int[1] would be 3, etc.

Any tips and ideas? I was thinking of implementing if charat(i) == ',' get the previous number(s) and parse them together and apply it to the current available slot in the array. But I'm not quite sure how to code that.

解决方案

You could read the entire input line from scanner, then split the line by , then you have a String[], parse each number into int[] with index one to one matching...(assuming valid input and no NumberFormatExceptions) like

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]);
}


As YoYo's answer suggests, the above can be achieved more concisely in Java 8:

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


To handle invalid input

You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.

If you don't need to know about invalid input but just want to continue parsing the array you could do the following:

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);

The reason we should trim the resulting array is that the invalid elements at the end of the int[] will be represented by a 0, these need to be removed in order to differentiate between a valid input value of 0.

Results in

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

If you need to know about invalid input later you could do the following:

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;
    }
}

In this case bad input (not a valid integer) the element will be null.

Results in

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


You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.

这篇关于将字符串数组转换为整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆