2016-04-28 56 views
1

我有一個.txt文件,格式爲整數,後跟一個浮點數,它們在每一行中由空格字符分隔。我想讀取每行的浮點數,然後將其放入數組中。 這裏是我到目前爲止的代碼,但是當我運行它,它給了我一個ArrayIndexOutOfBoundsException從一行讀取浮點數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(); 
      } 

所以,我怎麼能去第二個值?

回答

1

嘗試:

numbers = line.split("\\s+"); 
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

1

你試試這個regextester? numbers = line.split(" "); 問題在於你的正則表達式。通過調試器,您最好了解您的代碼問題。

相關問題