数字格式和索引越界。

Number format and index out of bound.

Java android 抱怨如何从字符串数组解析整数。我的字符串数组有将近 300 个数字。当我编写相同的代码但将其解析为浮点数时,代码工作正常我不想要十进制值。我只需要号码本身。它正在抛出 java.lang.NumberFormatException:无效的 int:“97.601006”。你介意告诉我我该怎么做吗?我还有一个问题。我想从我的算法 findPeaks 中获得峰值的 position/index(不是值本身)。当我执行 peaks.get(i) 时,系统也会崩溃并显示 IndexOutOfBoundsException: Invalid index 24, size is 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;
}

您可以使用 Math.round()。它将浮点值舍入为整数。要四舍五入你的价值,你必须首先将它从 String 解析为 double 。 替换你的行

int dataOfArray = Integer.parseInt(dataArray[i]);

int dataOfArray = Math.round(Double.parseDouble(dataArray[i]));

您使用“97.601006”的示例将得到 98。