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

3

由于我无法想出一种简单的方法将字符串数组转换为整数数组,所以我查找了一个方法示例,最终得到了以下代码:

private int[] convert(String string) {
    int number[] = new int[string.length()];

    for (int i = 0; i < string.length(); i++) {
        number[i] = Integer.parseInt(string[i]); // error here
    }
return number;
}

parseInt需要一个字符串,这就是string[i]的作用,但错误提示告诉我“表达式的类型必须是数组类型,但它解析为字符串”

我无法弄清楚我的代码有什么问题。

编辑:我是个傻瓜。谢谢大家,问题很明显。

4个回答

8

您试图像数组一样读取字符串。我猜想您试图逐个字符地遍历该字符串。为此,请使用 .charAt() 方法。

private int[] convert(String string) {
    int number[] = new int[string.length()];

    for (int i = 0; i < string.length(); i++) {
        number[i] = Integer.parseInt(string.charAt(i)); //Note charAt
    }
   return number;
}

如果你期望该字符串是一个字符串数组,但是在函数原型中缺少了数组标识符。请使用以下修正后的版本:

private int[] convert(String[] string) { //Note the [] after the String.
    int number[] = new int[string.length()];

    for (int i = 0; i < string.length(); i++) {
        number[i] = Integer.parseInt(string[i]);
    }
   return number;
}

IDE 告诉我应该是 Integer.parseInt(String.valueOf(string.charAt(i))) - behelit

4

您的代码出现了错误。请使用以下代码:

private int[] convert(String[] string) {
    int number[] = new int[string.length];

    for (int i = 0; i < string.length; i++) {
        number[i] = Integer.parseInt(string[i]); // error here
    }
    return number;
}

2

您的方法参数是一个字符串而不是字符串数组。 您无法使用string[i]访问字符串中的元素。 如果您想从字符串中实际获取单个字符,请使用'String.charAt(..)'或'String.substring(..)'。 请注意, charAt(..)将返回 char ,但这些很容易转换为字符串。


0
使用 Arrays.asList( YourIntArray ) 创建 ArrayList。
Integer[] intArray = {5, 10, 15}; // cannot use int[] here
List<Integer> intList = Arrays.asList(intArray);

或者,为了解耦两个数据结构:

List<Integer> intList = new ArrayList<Integer>(intArray.length);

for (int i=0; i<intArray.length; i++)
{
    intList.add(intArray[i]);
}

甚至更多:

List<Integer> intList = new ArrayList<Integer>(Arrays.asList(intArray));

#这对我有用


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接