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?
- Did you check for an output
"COULD NOT FIND TEXT.TXT"
? - add
System.out.println("Read: "+ pointset);
right afterint pointset = Integer.parseInt(p);
- Make sure you don't have
this.points = 0;
anywhere else. - You are defining
MrStan a = new MrStan();
insideMrStanReadFile
. Are you sure it's the same object as the one you use inclass todoTask
?
精彩评论