BufferedReader从txt文件到数组

时间:2016-03-05 23:49:54

标签: java android

在物理手机上测试Android应用。我正在使用Android Studio。我不知道为什么我会收到java.lang.IndexOutOfBoundsException:

Process: com.packtpub.libgdx.outtacluck.android, PID: 27731
java.lang.IndexOutOfBoundsException: Invalid index 4, size is 0
        at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
        at java.util.ArrayList.get(ArrayList.java:308)
        at com.packtpub.libgdx.outtacluck.game.WorldController.highScoreCheck(WorldController.java:1048)
        at com.packtpub.libgdx.outtacluck.game.WorldController.update(WorldController.java:375)
        at com.packtpub.libgdx.outtacluck.screens.GameScreen.render(GameScreen.java:40)
        at com.packtpub.libgdx.outtacluck.screens.DirectedGame.render(DirectedGame.java:67)
        at com.badlogic.gdx.backends.android.AndroidGraphics.onDrawFrame(AndroidGraphics.java:424)
        at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1531)
        at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1248)

但我的任何东西都没有被添加到scoresData数组

这是班级。我宣布它是相同的

public class ScoreManager {


public  List<Double> scoresData = new ArrayList<Double>();


public ScoreManager()
{
try{
        // Open the file that is the first
        FileInputStream fstream = new FileInputStream(Constants.SCORES_TRACKER);

        // Use DataInputStream to read binary NOT text.
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

        String strLine;


        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
            // Add number from file to list
            scoresData.add( Double.parseDouble(strLine));
        }
        //Close the input stream
        br.close();

        System.out.println(scoresData);
    }catch (Exception e){
        e.printStackTrace();
      }
    System.out.println("scoresData.size is " + scoresData.size());

    }

public static double parseInt(String input) throws NullPointerException, ParseException{
    if(input == null){
        throw new NullPointerException();
    }

    input = input.trim();

    NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
    ParsePosition parsePosition = new ParsePosition(0);
    Number number = numberFormat.parse(input, parsePosition);

    if(parsePosition.getIndex() != input.length()){
        throw new ParseException("Invalid input", parsePosition.getIndex());
    }

    return number.doubleValue();
}


public int getArrayElement(int index)
{
    if(scoresData.isEmpty())
    {
        System.out.println("scoresData is empty");
        return 0;
    }
    else
    {
        double x = scoresData.get(index);
        return (int) x;
    }
  }
}

1 个答案:

答案 0 :(得分:-2)

我刚测试了这个,它填充了arraylist就好了。根据上面的代码,我不认为你的arraylist声明是正确的。试试这个。

List<Double> scoresData = new ArrayList<Double>();