-
Help writing to a file getting an exception error
I have program i am trying to do. I was successful in checking to see if the file was created and if it was not created then creating it. Now I want to actually put data it the file and i am getting an exception error. Writing to a file should be very easy. Not sure where I am going wrong with this.
Code java:
import java.io.File;
import java.io.*;
import java.util.Formatter;
import java.util.Scanner;
/**
*
* @author Jamal
*/
public class Player {
private int wonAGame;
private int lostAGame;
private int addMoney;
private static String fPlayer;
private Formatter x;
Scanner sn = new Scanner(System.in);
public String getPlayerinfo() {
return fPlayer;
}
public void playerInfo(String fName) {
System.out.println("Please enter your first name: ");
String fname = sn.nextLine();
fPlayer = fname;
Player pr = new Player();
pr.checkPlayer(fname);
}
public void checkPlayer(String fname) {
File file = new File("C:\\test\\" + fPlayer + ".txt");
if (file.exists()) {
System.out.println("Weclome back" + " " + fPlayer);
} else {
System.out.println("Sorry not there");
try {
Formatter x = new Formatter("C:\\test\\" + fPlayer + ".txt");
System.out.println("File has been created");
} catch (Exception e) {
System.out.println("didn't work");
}
Player pr = new Player();
pr.writeFile();
}
}
public void writeFile() {
x.format("%s,%s", "LastName, First Name");
}
public void closeFile() {
x.close();
}
}
-
Re: Help writing to a file getting an exception error
made a mistake on tags, can someone instruct me again on how to do tags
-
Re: Help writing to a file getting an exception error
-
Re: Help writing to a file getting an exception error
Also, can you provide more information including exact errors and code which errors refer to.
-
Re: Help writing to a file getting an exception error
To guide you through this, I've made a quick demo of how you can write to a file using Formatter.
Code java:
import java.io.File;
import java.util.Formatter;
public class FormatterTest {
public static void main(String[] args) throws Exception {
final String fileName = "output.txt";
final File destination = new File(fileName);
if (!destination.exists()) {
destination.createNewFile();
}
final Formatter formatter = new Formatter(destination);
formatter.format("%s ####### %s", "Hello", "World");
formatter.flush();
formatter.close();
}
}
The reason I'm showing you this is so you can get to grips of what is needed to make a Formatter object do what you want.
There are numerous issues with your code, so by starting with cleaning up your Formatter implementation everything can go smoother.
Have a go with that, tweak your program and ask away when you've hit a brick wall.
With regards to your other problems, don't create multiple Player objects within a single Player object, refer to your methods directly inside the class, such as call writeFile(); instead of making a new player and calling pr.writeFile();
-
Re: Help writing to a file getting an exception error
I got it work thanks newbie. SO my problem was that I had many objects of the same class. I should of just created a new object to write to the file?
-
Re: Help writing to a file getting an exception error
Please attempt to format your code so that we can read it. It's difficult trying to understand someone else's code, why make it more harder than it has to be?
I usually use [code=java] [/code]
-
Re: Help writing to a file getting an exception error
Now I got the problem to work following newbie's advice. I just would like to know where my thinking went bad, so in the future I won't make this mistake, and possibly I can apply this logic to future problems.
-
Re: Help writing to a file getting an exception error
Hello,
I have gotten my program to work and do what I desire, but I still am getting java.lang.illegalStateException: Scanner closed error. The program is doing what it is suppose to be doing, but I don't understand on why I am getting an error. I believe it has to do with me closing the scanner, but I am unsure on how to properly close the scanner. Can someone please explain to me why this is giving me an error!!
Code java:
public class Player {
private int wonAGame;
private int lostAGame;
private int addMoney;
private static String fPlayer;
Scanner sn = new Scanner(System.in);
public String getPlayerinfo() {
return fPlayer;
}
public void playerInfo(String fName) {
System.out.println("Please enter your first name: ");
String fname = sn.nextLine();
fPlayer = fname;
Player pr = new Player();
pr.checkPlayer(fname);
}
public void checkPlayer(String fname) {
File file = new File("C:\\test\\" + fPlayer + ".txt");
if (file.exists()) {
System.out.println("Weclome back" + " " + fPlayer);
Player pr = new Player();
pr.readFile();
} else {
System.out.println("Sorry not there");
System.out.println("Would you like you to create a new file to start to play the game (1 = yes, 2 = no)?");
int playerResponse = sn.nextInt();
while (2 <= playerResponse) {
System.out.println("Would you like you to create a new file to start to play the game (1 = yes, 2 = no)?");
playerResponse = sn.nextInt();
}
if (playerResponse == 1) {
System.out.println("Please enter your first name");
Scanner ms = new Scanner(System.in);
String Fplayer = ms.nextLine();
System.out.println("Please enter your amount of money");
int amountMoney = ms.nextInt();
System.out.println("Welcome new Player");
System.out.println("Please enter your information below");
Player pr = new Player();
pr.writeFile(Fplayer, amountMoney);
}
try {
Formatter x = new Formatter("C:\\test\\" + fPlayer + ".txt");
System.out.println("File has been created");
} catch (Exception e) {
System.out.println("didn't work");
}
Player pr = new Player();
}
}
public void writeFile(String FPlayer, int Money) {
try {
Formatter formatter = new Formatter("C:\\test\\" + fPlayer + ".txt");
formatter.format("%s %s", FPlayer, Money);
formatter.flush();
formatter.close();
} catch (Exception e) {
System.out.println("didn't work");
}
Player pr = new Player();
pr.readFile();
}
public void readFile() {
try {
sn = new Scanner(new File("C:\\test\\" + fPlayer + ".txt"));
} catch (Exception e) {
System.out.println("could not find file");
}
while (sn.hasNext()) {
String a = sn.next();
String b = sn.next();
sn.close();
System.out.print("Hi"+" "+a+"\n"+"In your account you've this amount of money"+" "+b);
}
}
public void closefile(){
sn.close();
}
}
-
Re: Help writing to a file getting an exception error
I am having trouble closing the scanner
-
Re: Help writing to a file getting an exception error
Regarding:
Code :
while (sn.hasNext()) {
String a = sn.next();
String b = sn.next();
sn.close();
System.out.print("Hi"+" "+a+"\n"+"In your account you've this amount of money"+" "+b);
}
A very useful technique is to mentally step through your program "running" each line of code in your head as if you were the JVM. I recommend that you do this for this loop, and see what happens to your Scanner object when you do this. Based on your findings from this exercise, where would be the best code location to close your Scanner object?
-
Re: Help writing to a file getting an exception error
Yes, that makes perfect sense to close the scanner after the loop is done accessing the variables, but I have tried to close the scanner after the System.out.print and still to no avail. For example, when I move the sn.close method the program works without the error, it creates the the file, but no data is stored on it. If I leave the "sn.close" it's location I get the error, but it actually writes to the text file. So I am really unsure on why this is occurring.
-
Re: Help writing to a file getting an exception error
So it appears, I can continue on with the program logic and continue on with game, keep passing the error to other methods, and each method ducks the error, but inevitability it will throw the exception. I just cant' figure out to close the scanner correctly, when I do try and close the scanner outside of the while loop the program works but it doesn't write the code in the text file.
I feel would like to actually understand where my logic is failing me in this program. I am pleased that you're trying to help me.
Thanks.
-
Re: Help writing to a file getting an exception error
Quote:
Originally Posted by
loui345
Yes, that makes perfect sense to close the scanner after the loop is done accessing the variables, but I have tried to close the scanner after the System.out.print and still to no avail.
If you've made this attempt, you should show the code. For we know you still could be trying to close the Scanner inside of the for loop (after the System.out.println but before the closing brace), and only your code will show us if you're making this mistake. We can't help with what we can't see.
-
Re: Help writing to a file getting an exception error
Code java:
public class Player {
private int wonAGame;
private int lostAGame;
private int addMoney;
private static String fPlayer;
Scanner sn = new Scanner(System.in);
public String getPlayerinfo() {
return fPlayer;
}
public void playerInfo(String fName) {
System.out.println("Please enter your first name: ");
String fname = sn.nextLine();
fPlayer = fname;
Player pr = new Player();
pr.checkPlayer(fname);
}
public void checkPlayer(String fname) {
File file = new File("C:\\test\\" + fPlayer + ".txt");
if (file.exists()) {
System.out.println("Weclome back" + " " + fPlayer);
Player pr = new Player();
pr.readFile();
} else {
System.out.println("Sorry not there");
System.out.println("Would you like you to create a new file to start to play the game (1 = yes, 2 = no)?");
int playerResponse = sn.nextInt();
while (2 <= playerResponse) {
System.out.println("Would you like you to create a new file to start to play the game (1 = yes, 2 = no)?");
playerResponse = sn.nextInt();
}
if (playerResponse == 1) {
System.out.println("Please enter your first name");
Scanner ms = new Scanner(System.in);
String Fplayer = ms.nextLine();
System.out.println("Please enter your amount of money");
int amountMoney = ms.nextInt();
System.out.println("Welcome new Player");
System.out.println("Please enter your information below");
Player pr = new Player();
pr.writeFile(Fplayer, amountMoney);
}
try {
Formatter x = new Formatter("C:\\test\\" + fPlayer + ".txt");
System.out.println("File has been created");
} catch (Exception e) {
System.out.println("didn't work");
}
Player pr = new Player();
}
}
public void writeFile(String FPlayer, int Money) {
try {
Formatter formatter = new Formatter("C:\\test\\" + fPlayer + ".txt");
formatter.format("%s %s", FPlayer, Money);
formatter.flush();
formatter.close();
} catch (Exception e) {
System.out.println("didn't work");
}
Player pr = new Player();
pr.readFile();
}
public void readFile() {
try {
sn = new Scanner(new File("C:\\test\\" + fPlayer + ".txt"));
} catch (Exception e) {
System.out.println("could not find file");
}
//Right here is where the error is occuring
// "main" java.lang.IllegalStateException: Scanner closed
while (sn.hasNext()) {
String a = sn.next();
String b = sn.next();
System.out.print("Hi"+" "+a+"\n"+"In your account you've this amount of money"+" "+b);
Dice ce = new Dice();
ce.diceGenerator(b);
sn.close();
}
}
public void closefile(){
sn.close();
}
}
I am having trouble with closing the scanner. If I remove the method to close the scanner, the program will function correctly but it won't write to the text pad. Scanner does read the text pad as if information was actually written, but there is no data. If I leave the method to close the scanner in that place it works perfectly, I just have an exception error. I honestly don't know how to fix it. So can someone please explain where my logic is wrong.
-
Re: Help writing to a file getting an exception error
Again, you're closing your scanner inside of your while loop. Note that the while loop begins on the line with the while ( ... ) { and ends at the matching closing brace, }:
Code java:
while (sn.hasNext()) {
// all code from here
String a = sn.next();
System.out.print("Hi"+" "+a+"\n"+"In your account you've this amount of money"+" "+b);
Dice ce = new Dice();
ce.diceGenerator(b);
sn.close();
// to here are inside the while loop
}
All code inside the two braces are inside of the loop. Logic will tell you that since you're using the Scanner as part of your while boolean test, that you cannot close it inside of the loop. Logic will tell you the trivial solution: close the Scanner object outside of the loop, after the while loops closing curly brace, }.
Code java:
while (sn.hasNext()) {
String a = sn.next();
System.out.print("Hi"+" "+a+"\n"+"In your account you've this amount of money"+" "+b);
Dice ce = new Dice();
ce.diceGenerator(b);
}
sn.close();
A key learning point to use of the forum: always try to illustrate what you're doing by showing the pertinent code. It really is worth a thousand words and would have saved a lot of time if shown earlier.
-
Re: Help writing to a file getting an exception error
Yes,
I understand the point you're trying to make, but if I close the scanner outside of the while loop the program will not write to the text file. I end up with a blank text file. Leaving my scanner in the place that you see allows me to write the data to the text file, but the result of that is that I am getting an exception error. Does this make sense to you?
-
Re: Help writing to a file getting an exception error
OK, let me look at the rest of your code in greater depth...
-
Re: Help writing to a file getting an exception error
Your code confuses me quite a bit, and part of it is because of your god-class, Player, since it seems full of lots of code that has little to do with the essence of being a Player object. I think that you need to first do some serious refactoring here, some cleaning up. I'd make Player just responsible for the essence of being a Player -- meaning it has a name, money, perhaps a record of games won and lost, methods and constructors to set and change this information and extract this information and that's it. Something like this:
Code :
class Player2 {
private String name;
private int money;
public Player2(String name, int money) {
this.name = name;
this.money = money;
}
public Player2(String name) {
this(name, 0);
}
public String getName() {
return name;
}
public int getMoney() {
return money;
}
// could add negative amount if want to
// take money
public void addMoney(int add) {
// ...
}
@Override
public String toString() {
// .... return a String that has the properties of this object
}
}
And then I'd create another class, say PlayerIO that simply concerns itself with IO aspects including writing the Player data to disk and reading it out again. Then I'd create another class called Game that was involved with creating a Player or two, setting up the game and having Player play the game.
-
Re: Help writing to a file getting an exception error
Okay, great I totally understand your logic, but if i still clean the code up I still don't understand where I went wrong with scanner method. It works as long as the close is in the while loop.
I will clean the code up as you suggested, but I don't to comeback in a few hours with the same question I had before.
Again, thanks for taking the time to help me.
-
Re: Help writing to a file getting an exception error
Quote:
Originally Posted by
loui345
Okay, great I totally understand your logic, but if i still clean the code up I still don't understand where I went wrong with scanner method. It works as long as the close is in the while loop.
I'm not sure either because your code is going every which way but loose. For instance when you read the Player data in in the readFile() method, where do you save it to a variable that is available to the class *anywhere*?
-
Re: Help writing to a file getting an exception error
Yes, I saved the data to into Strings using the scanner next method, which seems to work.
-
Re: Help writing to a file getting an exception error
Quote:
Originally Posted by
loui345
Yes, I saved the data to into Strings using the scanner next method, which seems to work.
But where do you save this data as I don't see it in the readFile() method that you've posted? And besides, the Player information should be saved as a Player object, not Strings, right?
-
Re: Help writing to a file getting an exception error
I am sorry, i misunderstood you. My intentions was to read the text file store the information into variables, which then would allow me to manipulate the data. That what I thought you was asking earlier. I am unsure on what you're asking me about my readFile method.
-
Re: Help writing to a file getting an exception error
The question is what is the purpose of the readFile()? Is to simply print out what is held in the file, to just display it? Or is it to convert the data held into Player objects? Because if the latter, it does nothing of the kind.
Regardless, you will need to do some serious refactoring and cleaning of that code.