EDIT: I am trying to create a "clicker" game, that loads the last recorded number from the data file.
I am working on a simple, one button game, it is a clicker game. Nothing fancy, just a JButton and a JLabel. I'm fairly new at the Java IO Class, so I don't know what's causing this to happen. I'm not getting any errors, but a random number, except the same number every time.
Write Method:
public static void write(long data) {
File file = new File("data.txt");
path = file.getAbsolutePath();
try {
PrintWriter writer = new PrintWriter(file);
writer.println(data);
writer.close();
} catch (IOException e) {
System.out.println(e);
}
}
Read Method:
public static long read() {
long data = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(path));
data = reader.read();
reader.close();
return data;
} catch (IOException e) {
System.err.format("Exception occurred trying to read '%s'.", path);
e.printStackTrace();
return 0;
}
}
Graphical User Interface:
public static void gui() {
. . .
// Declarations {
JFrame frame = new JFrame("Clicker");
JPanel panel = new JPanel();
JButton clickerButton = new JButton("Click");
JLabel amountOfClicks = new JLabel("Click to get started!");
// }
. . .
// * * * * * * * * * * *
panel.setLayout(new GridLayout(2, 0));
// Action {
clickerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
if (read() >= 1) {
clickerCount = read() + 1;
amountOfClicks.setText("You have clicked: " + clickerCount + " times.");
write(clickerCount);
} else {
clickerCount = clickerCount + 1;
amountOfClicks.setText("You have clicked: " + clickerCount + " times.");
write(clickerCount);
}
}
});
// }
. . .
Also the random number I get (48), when I click the button it should increase by 1. But now since it starts at "48", first click: increases by 1. Second: 4. Third: 1. Then stops increasing. The reason why I'm wanting to write to a file is so, I can load the last recorded number.