我试图将一串数字(例如“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)没有准确捕获我的字符串。有谁能发现可能出错的地方?
谢谢。
答案 0 :(得分: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]
我没有看到问题?
答案 1 :(得分: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());
}
答案 2 :(得分:-1)
short
,并且您尝试添加java.lang.Short
对象。
编辑我错了......