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

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

问题描述

因为我无法找出一个简单的方法来我的字符串数组转换为整数数组,我抬头一看一个例子的方法和这里是我结束了:

Since I couldn't figure out an easy way to convert my string array into an integer array, I looked up an example for a method and here is what I ended up with:

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函数需要一个字符串,字符串是什么[i]为,但错误告诉我之类的前pression的必须是一个数组类型,但它解析为字符串

parseInt requires a string which is what string[i] is but the error tells me "The type of the expression must be an array type but it resolved to String"

我无法弄清楚什么是我的code中的问题。

I can't figure out what is the problem with my code.

编辑:我是个白痴。谢谢大家这是显而易见的。

I'm an idiot. Thanks all it was obvious.

推荐答案

您正试图读取一个字符串,就好像它是一个数组。我假设你想在一个时间去串一个字符。要做到这一点,使用.charAt()

You're trying to read a string as if it were an array. I assume you're trying to go through the string one character at a time. To do that, use .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;
}

如果你期望的字符串,字符串数组,但是,你冷落在函数原型的阵列标识。使用以下更正版本:

If you expect the string to be an array of strings, however, you left out the array identifier in the function prototype. Use the following corrected version:

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

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

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