Java android抱怨如何从String数组中解析Integer。我的字符串数组有近300个数字。当我做相同的代码,但解析为浮动,代码工作正常,我不想要小数值。我只需要数字本身。抛出 java.lang.NumberFormatException:Invalid int:“97.601006”。你介意告诉我该怎么做。我还有一个问题。我想从我的算法 findPeaks 获得峰值的位置/索引(不是值本身)。当我执行 peaks.get(i)时,系统也会崩溃并说 IndexOutOfBoundsException:索引24无效,大小为1 提前致谢。
String Adata = String.valueOf(stringBuilder);
String dataArray[];
dataArray = Adata.split("\\s+");
Log.i("TAG", "Size of dataArray: " + dataArray.length);
List String_TO_List = new ArrayList<Integer>();
int lastLength = dataArray.length - 1;
for (int i = 0; i < lastLength; i++) {
//the console pointed at this line with number format exception
int dataOfArray = Integer.parseInt(dataArray[i]);
if (dataOfArray > 170) {
String_TO_List.add(dataOfArray);
}
}
Log.i("TAG", "Size of list: " + String_TO_List.size());
List<Integer> List_Of_Peaks = findPeaks(String_TO_List);
Log.i(TAG, "Peaks" + List_Of_Peaks);
Peaks_num.setText(String.valueOf(List_Of_Peaks));
//my algorithm to find the peaks.
ArrayList<Float> peaks = new ArrayList<Float>();
float x1_n_ref = 0;
int alpha = 0; //0=down, 1=up.
int size = points.size();
for (int i = 0; i < size; i+=4) {
float IndexValues = points.get(i);
float delta = x1_n_ref - IndexValues;
if ( delta < 0) {
x1_n_ref = IndexValues;
alpha = 1;
} else if (alpha == 1 && delta > 0) {
peaks.add(x1_n_ref);
// here the system complain with Index exception. I want to know the poition or the index of the peak value so I can pass it to setText or Toast message.
peaks.get(i);
Log.i("TAG", "peak added: " + x1_n_ref);
alpha = 0;
} else if (alpha == 0 && delta > 0) {
x1_n_ref = IndexValues ;
}
//}
}
return peaks;
}
答案 0 :(得分:1)
您可以使用Math.round()。它将浮点值舍入为整数。要舍入您的值,您必须首先将其从String解析为double。 替换你的行
int dataOfArray = Integer.parseInt(dataArray[i]);
与
int dataOfArray = Math.round(Double.parseDouble(dataArray[i]));
您的“97.601006”示例将导致98。