开发者

My program isn't reading the file as it's supposed to be

I'm trying to make a int value, which goes up by a counter every second, then when you close the program down, it will the save the value to a .txt file, and then, it SHOULD, when you start up the program again, read the int value from the file, and continue from that value again, however, it is saving correctly, it makes the file, but when I startup my program again, it will just start at 1 again, and not at the value which was saved in the .txt file.

The int value:

    public int points;

The getter and setter, located in MrStan.class

    public int getPoints(){
开发者_JS百科    return points;
}

public void setPoints( int points ){
    this.points = points;
}

How i'm reading the file:

        MrStanReadFile r = new MrStanReadFile();
    r.openFile();
    r.readFile();
    r.closeFile();

My ReadFile class:

public class MrStanReadFile {

private Scanner x;
MrStan a = new MrStan();

public void openFile(){
    try{
        x = new Scanner(new File("D:/MrStan/text.txt"));
    }catch(Exception ex){
        System.out.println("COULD NOT FIND TEXT.TXT");
    }
}

public void readFile(){
    while(x.hasNext()){
        String p = x.next();
        int pointset = Integer.parseInt(p);
        a.setPoints(pointset);
    }
}

public void closeFile(){
    x.close();
}

}

Other places where the int is used:

Todotask:

    public MrStan(){
    timer.schedule(new todoTask(), 0, 1 * 1000);
}

class todoTask extends TimerTask{
    public void run(){  
        points++;
        repaint();
    }
}

private Timer timer = new Timer();

and

        g.drawString("Points: " + points, 75, 83);

Okay, at the readFile method, you will see a string, p, that's the string in the text file. I convert the string to an int, using Integer.parseInt(), then, I set my int value to the converted pointset value, but it isn't changing, how will my program work so it will start up from the number set in the .txt file?


  1. Did you check for an output "COULD NOT FIND TEXT.TXT"?
  2. add System.out.println("Read: "+ pointset); right after int pointset = Integer.parseInt(p);
  3. Make sure you don't have this.points = 0; anywhere else.
  4. You are defining MrStan a = new MrStan(); inside MrStanReadFile. Are you sure it's the same object as the one you use in class todoTask?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜