从行读取float会抛出ArrayIndexOutOfBoundsException

时间:2016-04-28 12:12:09

标签: java android indexoutofboundsexception

我有一个.txt文件,其格式为整数,后跟浮点数,它们由每行中的空格字符分隔。我想从每一行读取浮点数,然后将其放入数组中。 到目前为止,这是我的代码,但是当我运行它时,它会给我一个ArrayIndexOutOfBoundsException

因为我猜它永远不会创建第二个值:

BufferedReader reader = null;
            try{
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(
                        new File(root.getAbsolutePath().toString()+"/samplefile.txt"))));
                String line = null;
                String[] numbers = null;
                int i = 0;
                value.clear();
                while((line = reader.readLine()) != null){
                    numbers = line.split("/\\s/");
                    value.add(Float.valueOf(numbers[1].trim()));
                }
                mTextview5.setText(String.valueOf(value.get(1)));
            }catch(IOException e){
                e.printStackTrace();
            }

那么我怎样才能获得第二个价值呢?

3 个答案:

答案 0 :(得分:1)

尝试:

numbers = line.split("\\s+");

答案 1 :(得分:1)

您是否尝试使用调试器? 你会得到一个非常快的结果,程序停止并崩溃。

arraylist(您的值)不应抛出ArrayIndexOutOfBoundsException。 我的猜测是你可能有错误的正则表达式。

numbers = line.split("/\\s/");
numbers[1] # there is a possibility that your "split regex" 
#returns a smaller array than expected, thus ArrayIndexOutOfBoundsException.

尝试像http://www.regexplanet.com/advanced/java/index.html

这样的正则表达式

答案 2 :(得分:1)

你尝试过这个吗? numbers = line.split(" "); 问题是你的正则表达式。使用调试器,您最好了解代码的问题。

相关问题