0

我正在尝试将一串数字(例如“34 4 5 6 67 45 34”)转换为短裤数组。

我写了以下代码:

//Split the string and then build a short array with the values.
            String[] tabOfShortString = finalString.split(" ");
            int length = tabOfShortString.length;
            System.out.println("Length of float string is" + length);
            short[] shortsArray = new short[length];
            for (int l = 0; l < length; l++) {
                //System.out.println("l is currently "+l);
                Short res = new Short(tabOfShortString[l]);
                System.out.println("Indice Short Value is " + res);
                shortsArray[l] = res;
            }

问题是完成的数组(shortsArray)没有准确地捕获我的字符串。谁能发现可能出了什么问题?

谢谢你。

4

3 回答 3

0

您的解决方案对我有用,这就是我所拥有的:

public static short[] toShorts(String finalString) {
    String[] tabOfShortString = finalString.split(" ");
    int length = tabOfShortString.length;
    System.out.println("Length of float string is" + length);
    short[] shortsArray = new short[length];
    for (int l = 0; l < length; l++) {
        //System.out.println("l is currently "+l);
        Short res = new Short(tabOfShortString[l]);
        System.out.println("Indice Short Value is " + res);
        shortsArray[l] = res;
    }

    return shortsArray;

}

然后我称之为:

short[] qux = toShorts("34 4 5 6 67 45 34");

qux 的输出是:

[34, 4, 5, 6, 67, 45, 34]

我看不出问题?

于 2012-05-16T15:24:38.873 回答
0

首先使用 StringTokenizer 打破它,您必须计算字符串中空格的数量,然后应用循环从字符串中提取值

int count=0;
String text= "34 4 5 6 67 45 34";

for(int i=0; i<text.length(); i++)
{
while(text.charAt(i)==' ')
{
count++;
}
}

StringTokenizer st = new StringTokenizer(String);

for(int j=0;j<count;j++){
Short res[] = new Short(st.nextToken());

}
于 2012-05-16T15:28:21.500 回答
-1

也许是因为您的数组是原始类型short并且您尝试添加一个java.lang.Short对象。

编辑我错了...

于 2012-05-16T14:51:51.987 回答