Setting number in a file to 0 when pressing a JButton - java

In the starting menu for my game I wan't to make it so that when you press the "Continue" button you get the score that you had the last time you played. I have already fixed the code that saves the score and the code that loads the score so it isn't any problems with the continue button.
But for the "New Game" button I'm having some difficulties. When that button is pressed I need to make the file that stores the score reset (set the number inside it to 0 instead of the last score). I have tried to have this code inside the ActionListener for the button but it doesn't set the text inside the .dat file to 0 but it adds a 0 to the end.
try{
String zero = "0";
byte[] reset = zero.getBytes();
player.getFile().write(reset);
}catch (IOException ex){
}
I have also tried player.setScore("0"); which I use to add 10 score every time an enemy dies but then it will still get the score from the .dat file.
This is the two method inside the player class that handels the loading and saving of the file.
public void save(){
try{
getScore = new File("Score.dat");
scoreFile = new FileOutputStream(getScore);
byte[] saveScore = score.getBytes();
scoreFile.write(saveScore);
}catch(FileNotFoundException ex){
}catch(IOException ex){
}
}
public void load(){
try{
br = new BufferedReader(new FileReader("Score.dat"));
score = br.readLine();
}catch (FileNotFoundException ex){
}catch(IOException ex){
}
}
I have also tried to only run the load() method if I press the "Continue" button and not the "New Game" button but the I get a java.lang.NullPointerException error.

Your code is hiding all the relevant exceptions, which will make it very hard to figure out what's going on - put something like ex.printStackTrace(); in the catch blocks so you can see if exceptions are thrown. I would imagine in your case, the bytes aren't getting written because you aren't closing or flushing the stream.
Regardless, you probably want to use something like a PrintWriter with the file instead, rather than writing raw bytes:
PrintWriter writer = new PrintWriter(new File("file.txt"));
writer.println("0");
writer.close();

If getFile() returns a FileWriter, then you probably have to close and reopen the file each time, and use the constructor that lets you indicate that you do NOT want it to append additional data.

Related

Loading data from an RPG game

So I'm working on a simple RPG game. I want to add an option to load progress through the game, but I guess I'm not that familiar with Java to do it without issues. The idea is to save the game on checkpoints, and load a saved data when the game continues. I'm getting an error with a loadGame method, and I guess it's related to the fact that the data I'm trying to load are all different data types. health and level are integers, while equippedItem is a string.
Here are just two methods, saveGame, and loadGame, because the code is a bit too long to simply paste it in the whole. I'll put additional code if needed of course.
public static void saveGame() {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("savedGame.txt"));
bw.write("Your health is " + player.getHealth());
bw.newLine();
bw.write("Your level is " + player.getLevel());
bw.newLine();
bw.write("" + player.equippedItem);
bw.close();
}
catch (Exception e) {
System.out.println("There's an error.");
}
}
The saveGame() doing its work well, it stores the data in the file. The issue is with the loadGame() method.
public void loadGame() {
try {
BufferedReader br = new BufferedReader(new FileReader("savedGame.txt"));
player.getHealth();
player.getLevel();
player.equippedItem;
br.close();
} catch (Exception e) {
System.out.println("There's an error.");
}
}
The result of player.getHealth() and player.getLevel() is ignored, and it's probably the data type issue I've mentioned.
What you're doing is creating a text file in saveGame(), 'opening' that save file in loadGame() but not accessing the data inside.
You have correctly created a BufferedReader, but you're using it incorrectly. You will need to use br.readLine() to read the text file which will return a string like "Your health is 123".
To update the state of the player with this data, you could add something like this inside loadGame():
player.setHp(parseHp(br.readLine()));
player.setLevel(parseLevel(br.readLine()));
... // and so on
The parse methods would take a String input like "Your health is 123" and return int 123.

Can't write to the file second time after the program is closed and run again. Only save for the first time

I was working on my assignment and found that the textfile which I suppose to write data to,
Data cannot be written twice to it once I close the program and run again. Here is the code
public static void writeFile() {
try {
PrintWriter writeFile = new PrintWriter(file);
writeFile.print(buttonC1.getText()+"\t"+
stdname.getText()+"\t"+mtcnum.getText()+"\t"+cid.getText()+
"\t"+spvname.getText()+"\r\n123");
writeFile.close();
}catch(Exception e){
e.printStackTrace();
}
}
How is "file" created? Is a stacktrace printed? In the catch block, print e.getMessage().
Try this:
FileWriter writer = new FileWriter("test.txt");
try(PrintWriter printWriter = new PrintWriter(writer)){
printWriter.write("Happy days are here again!");
}
After the above works, add in your content one step at a time. It is possible one of those elements is causing an issue, like a NullPointerException.

How can I plus file's info?

I'm making a new game and I wanna make a coins collector to, later, buy things with those coins. I'm using eclipse.
void save() {
try {
PrintWriter out = new PrintWriter("coins.txt");
out.write(Integer.toString(nmonedas));
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void load() {
StringBuffer texto=new StringBuffer();
try {
int c;
#SuppressWarnings("resource")
FileReader entrada=new FileReader("coins.txt");
while((c=entrada.read())!=-1){
texto.append((char)c);
}
}
catch (IOException ex) {}
labelshow.setText(texto.toString());
}
I have this code but i cant plus the info. NEED HELP PLS
Well, the thing is, I'm doing a game in eclipse and I want you to collect coins and keep them in a file.
They are collected perfectly and stored in the file, but when I start the game again I want them to be collected but they add up with the previous ones
I assume you are referring to appending text to a .TXT file. If so, you can use something like this:
Files.write(Paths.get("Path to text file here"), "Content".getBytes(), StandardOpenOption.APPEND);
I would put the above in a TRY CATCH block. Also look into PrintWriter as this may be more appopriate to what you need it for as it allows you to continuously write to the file.

java.util.NoSuchElementException when using Scanner.next()

Java noob working on a project where I'm supposed to display data obtained from a text file onto grids. Project is essentially written, but output displays this exception:
run:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at inputOutput.ReadDataFile.populateData(ReadDataFile.java:50)
at boggle.Boggle.main(Boggle.java:27)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Boggle.java:27 links to a line of code in the main method of my superclass Boggle.java. The line is supposed to call one of the methods in my class ReadDataFile.java. The line reads dataRead.populateData(); (//2. on the comments below), and in context the main method looks like:
public static void main(String[] args) { //main() method begins
// TODO code application logic here
ReadDataFile dataRead = new ReadDataFile("BoggleData.txt"); //1. instance of class ReadDataFile created
dataRead.populateData(); //2. populateData() method called
boggleData = dataRead.getData(); //3. member variable set equal to getData() method
Board boggleBoard = new Board(boggleData); //4. instance of class Board created, passing data as argument
boggleBoard.shakeDice(); //5. shakeDice() method called
} //main() method ends
ReadDataFile.java:50 links to a line in a method called populateData() inside of my subclass ReadDataFile.java. The line is input.next(); and it's in the finally component of a try-catch-finally I created for the class. In context, the populateData() method looks like:
public void populateData(){ //populateData() method begins
try{ //try begins
URL url = getClass().getResource(dataFile); //1. instance of class URL created from file name
File file = new File(url.toURI()); //2. instance of class File based on url
input = new Scanner(file); //3. member variable initialized based on file
while(input.hasNext()){ //4. while loop goes through data file
data.add(input.next()); //a. data from file added to ArrayList
}
} //try ends
catch(Exception ex){ //catch begins
System.out.println(ex.toString());
ex.printStackTrace();
} //catch ends
finally{ //finally begins
input.next();
} //finally ends
} //populateDate() method ends
Basically, I'm having trouble figuring out how I can get around this exception. The actual goal of the project is to display data in grids, but I only get a notice that an exception has been found in the output. The code compiles fine, so I'm not worried about misplaced semicolons or incorrect data types. I'm new to the Java language, and while books and other stackoverflow questions have solved some of my problems, this exception has gotten me stuck.
Would anybody be able to provide some feedback on just what I need to do to get around the exception showing up in my output, what's causing it, or at least steer me in the right direction? I'd really appreciate any helpful comments. Thanks.
Your exception stack-trace shows where the problem is:
at inputOutput.ReadDataFile.populateData(ReadDataFile.java:50)
At line 50 you have this:
finally{ //finally begins
input.next();
}
The problem is that you have already exhausted the file with a loop you previously executed:
while(input.hasNext()){ //4. while loop goes through data file
data.add(input.next()); //a. data from file added to ArrayList
}
I think you meant to close in your finally.
finally{ //finally begins
input.next();
}
should (almost certainly) be
finally{
input.close();
}
Or you could use try-with-resources to close your Scanner like
public void populateData(String dataFile) {
try {
URL url = getClass().getResource(dataFile);
File file = new File(url.toURI());
try (Scanner input = new Scanner(file)) {
while (input.hasNext()) {
data.add(input.next());
}
}
} catch (Exception ex) {
System.out.println(ex.toString());
ex.printStackTrace();
}
}

ObjectOutputStream writing array to file with inherited classes not writing to file

My assignment is to save a list of employees as a binary file (and later read from it). I'm working on the output portion now, below is the block of the function that is in question. This function does have about 10 more lines but they edit things on the TextField arraylist.
The Employee class is the parent of both the Supervisor and Secretary classes. all is the ArrayList that holds all the employee, secretary, and employee objects.
I'm using netbeans 8.0.2, when the program runs and I click the save button in the gui (onActionEvent() is this function) there are no compiler errors. The "IO Error" or "No Permissions..." doesn't output. Ive tried saving both with and without the employees.dat file being already created.
I'm not really sure what to do at this point, I contemplated saving each object as a the collection of int, String, etc but that's dumb, it should be able to work this way... right?
EDIT:
Employee, Supervisor, and Secretary are all Serializable.
private void saveChanges(ArrayList<Employee> all, ArrayList<TextField> text, int index) {
try ( ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("employees.dat", true)); ) {
for (int i = 0; i < all.size(); i++) {
if (all.get(i).getClass() == (new Secretary().getClass()))
output.writeObject(new Secretary((Secretary) all.get(i)));
else if (all.get(i).getClass() == (new Supervisor().getClass()))
output.writeObject(new Supervisor((Supervisor) all.get(i)));
else
output.writeObject(new Employee(all.get(i)));
}
output.flush();
} catch (IOException io) {
io.printStackTrace();
} catch (SecurityException se) {
se.printStackTrace();
}
}
EDIT:
I have edited the try-catch to this code...
try ( ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("employees.dat", true)); ) {
output.writeObject(all);
output.flush();
output.close();
} catch (IOException io) {
io.printStackTrace();
} catch (SecurityException se) {
se.printStackTrace();
}
Still not writing to file. I have permissions in the folder the .java files are in.
try ( ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("employees.dat", true)); ) {
Change true to false, or remove it. You can't append to files created as object output streams, at least not like this, and it's debatable whether you're even supposed to be doing so.
for (int i = 0; i < all.size(); i++) {
if (all.get(i).getClass() == (new Secretary().getClass()))
output.writeObject(new Secretary((Secretary) all.get(i)));
else if (all.get(i).getClass() == (new Supervisor().getClass()))
output.writeObject(new Supervisor((Supervisor) all.get(i)));
else
output.writeObject(new Employee(all.get(i)));
}
Change this entire mess to this:
output.writeObject(all);
If this still doesn't work there must have been an exception somewhere, and you're just going to have to find it, print it, and post it. Edit it into your question. Or else you're looking at the wrong file.
NB you will also have to change the code that reads the file, to just read the list in a single readObject() call.
By any chance are you happening to write an applet or JNLP without appropriate permissions?
do you have write access to the folder that you are outputting the file ? (which in this case is the directory that the program is running in. )
I would recomend calling io.printStackTrace() and se.printStackTrace(); in the exception handlers to provide significantly more information about the exceptions.
At the end of the file writing also dont forget to call output.close() to ensure that the stream is closed properly, the tail of the data is written and there are no left over open file handles on your system.

Categories

Resources