-1

I am having to make a gui project for my CSIS class and I am having trouble with the read and Write I am using. I am making a game where you battle stuff and after you beat five of them it shows a message saying "YOU WIN". Every time you win a battle, I have it write the number of wins to a file so if you were to close the game you can continue when it is opened again. Here is the code that i have Written - this is my read method.

    private static int read() 
{
    int returnValue = 0;
    try(Scanner reader = new Scanner("wins.txt"))
    {
        while(reader.hasNextLine())
        {
            String read = reader.nextLine();
            returnValue = Integer.parseInt(read);
        }
    }
    catch(NullPointerException e)
    {
        System.out.println("No such File! Please Try Again! " + e.getMessage());
    }
    return returnValue;

and this is my Write method.

    private static void write(int wins) 
{
    try(Formatter writer = new Formatter("wins.txt");)
    {
        writer.format("%d", wins);
    } 
    catch (FileNotFoundException e) 
    {
        System.out.println("File not Found!!");
    }

}

the only thing that is in the wins.txt file is the number that the Write method writes into it. so i win once then the file will have "1" and if i win twice then it will have "2"

Whenever I run the program, it throws a NumberFormatException. I am not sure why it is doing this because I am parseing the String that that reader reads into an int.

Jared27
  • 23
  • 1
  • 1
  • 5

1 Answers1

0

The problem is that this code...

Scanner reader = new Scanner("wins.txt")

... constructs a Scanner with the literal text "wins.txt", not the contents of the file "wins.txt".

To read a file with a Scanner, the easiest way for you is probably to construct it using a File object...

Scanner reader = new Scanner(new File("wins.txt"))

There are some other changes you will need to make to your code to get it to work from this point, but this should cover the major issue.

clstrfsck
  • 14,715
  • 4
  • 44
  • 59