简体   繁体   中英

Making a highscore function that writes the score to a file in java

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;


public class GameRunner {

    public static void main(String[] args) {
        Scanner scan = new Scanner (System.in);
        System.out.println("Welcome to blackjack!\nEnter your name please.");

        String name = scan.nextLine();

        System.out.println("Here are your cards " + name);


        Deck theDeck = new Deck(1, true);

        if (mySum > dealerSum && mySum <= 21 || dealerSum > 21){
            System.out.println("You win!");
        }//if
        else if (mySum == dealerSum) {
            System.out.println("It's a draw!");
        }//else
        else {
            System.out.println("Dealer wins!");
        }

    }//main

    public void highScore() throws IOException{
        File myFile=new File("highscore.txt");
        FileWriter fw=new FileWriter(myFile, true);
        String end= "You have beaten the dealer " + "times.";
        fw.write(end);
        fw.close();

    }

}

This isn't all of my code, but I want it to count the number of times the user wins and stop when the dealer wins, and then write the number, which is their high score, into a file. Also, my file is not showing up when I refresh or run my program and I have searched everywhere for it.

Make sure your flush it.

fw.flush();

As well as you create the .txt before hand.

myFile.createFile();

Read this please, http://docs.oracle.com/javase/tutorial/essential/io/file.html

The highScore function seems to save "something". But you never actually call it. And even if you call it, it will write only this line in it:

You have beaten the dealer times.

It doesn't make sense. It looks as if you want to write a number N in "beaten the dealer N times", but you're not doing that. As such, this code looks incomplete, as if you stopped writing it in the middle.

If you do call this method, then a file will be created. Since in new File("highscore.txt"); you used the relative path "highscore.txt" , the file will be created in the execution directory. If you run this from an IDE, then the execution directory is typically the project's directory. Another alternative is to use an absolute path, for example "c:/highscore.txt" , then you can definitely easily find it.

Above stated answer is absolutely right but u can also save it statically nd just increase the counter number if u want to show how many times he has bitten by using simple char at function. Nd clearing the file text with new text or just by replacing the number by replace function of string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM