Java 将字符串数组转换为整数数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18838781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:32:27  来源:igfitidea点击:

Converting String Array to an Integer Array

javastringintegeruser-inputdata-manipulation

提问by Mario

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.

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

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.

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

采纳答案by Java Devil

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[]每个数字解析为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]);
}


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

正如YoYo 的回答所暗示的那样,上述内容可以在 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.

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

Results in

结果是

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

输入:"2,5,6,bad,10"
输出:[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]

输入:"2,5,6,bad,10"
输出:[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.

您可以通过不捕获异常(有关更多信息,请参阅此问题)并使用不同的方法检查有效整数来潜在地提高性能。

回答by Shreyansh

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class MultiArg {

    Scanner sc;
    int n;
    String as;
    List<Integer> numList = new ArrayList<Integer>();

    public void fun() {
        sc = new Scanner(System.in);
        System.out.println("enter value");
        while (sc.hasNextInt())
            as = sc.nextLine();
    }

    public void diplay() {
        System.out.println("x");
        Integer[] num = numList.toArray(new Integer[numList.size()]);
        System.out.println("show value " + as);
        for (Integer m : num) {
            System.out.println("\t" + m);
        }
    }
}

but to terminate the while loop you have to put any charecter at the end of input.

但是要终止 while 循环,您必须在输入的末尾放置任何字符。

ex. input:

前任。输入:

12 34 56 78 45 67 .

output:

输出:

12 34 56 78 45 67

回答by YoYo

Line by line

逐行

int [] v = Stream.of(line.split(",\s+"))
  .mapToInt(Integer::parseInt)
  .toArray();

回答by Ritam Chakraborty

Stream.of().mapToInt().toArray()seems to be the best options.

Stream.of().mapToInt().toArray()似乎是最好的选择。

int[] arr = Stream.of(new String[]{"1", "2", "3"})
                  .mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));