Java 掷硬币游戏保存问题

Java 掷硬币游戏保存问题,java,Java,我正在为一项任务创建一个掷硬币游戏,保存你的最后一个高分和名字。如果没有高分文件,程序运行正常,但如果有文件,程序将停止工作 import java.util.Scanner; import java.io.File; import java.io.FileWriter; import java.io.PrintWriter; public class BradySkuza43 { public static void main( String[] args ) throws Except

我正在为一项任务创建一个掷硬币游戏,保存你的最后一个高分和名字。如果没有高分文件,程序运行正常,但如果有文件,程序将停止工作

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


public class BradySkuza43
{

public static void main( String[] args ) throws Exception
{
    Scanner keyboard = new Scanner(System.in);

    String coin, again, bestName, saveFile = "coin-flip-score.txt";
    int flip, streak = 0, best;

    File in = new File(saveFile);
    if ( in.createNewFile() )
    {
        System.out.println("Save game file doesn't exist. Created.");
        best = 1;
        bestName = " ";
    }
    else
    {
        Scanner input = new Scanner(in);
        bestName = input.next();
        best = input.nextInt();
        input.close();
        System.out.println("High score is " + best + " flips in a row by " + bestName );
    }

    do
    {
        flip = 1 + (int)(Math.random()*2);

        if ( flip == 1 )
        {
        coin = "HEADS";
        }
        else
        {
        coin = "TAILS";
        }

        System.out.println( "You flip a coin and it is... " + coin );

        if ( flip == 1 )
        {
            streak++;
            System.out.println( "\tThat's " + streak + " in a row...." );
            System.out.print( "\tWould you like to flip again (y/n)? " );
            again = keyboard.next();
        }
        else
        {
            streak = 0;
            again = "n";
        }
    } while ( again.equals("y") );

    System.out.println( "Final score: " + streak );

    if ( streak > best )
    {
        System.out.println("That's a new high score!");
        System.out.print("Your name: ");
        bestName = keyboard.next();
        best = streak;
    }
    else if ( streak == best )
    {
        System.out.println("That ties the high score. Cool.");
    }
    else
    {
        System.out.println("You'll have to do better than " + streak + "if you want a high score.");
    }


    PrintWriter out = new PrintWriter( new FileWriter(saveFile) );
    out.println(bestName);
    out.println(best);
    out.close();
}
}

当已经存在一个文件时,我得到一个NoTouchElement错误。我假设它与导入功能有关,但我不知道如何修复它。

以下是一些建议:

  • 您的高分文件的名称不会更改,对吗?它不应该是一个变量,它应该是一个
    静态final
    变量
  • 玩游戏,然后决定这是否是一个高分。因此,您应该有一个
    getHighScore()
    方法(可以是
    static
  • 如果新分数是高分,则将其写入高分文件。应该有一个方法
    静态writeHighScore(最终字符串名,最终整数分数)
  • 所以我想把你的程序改成这样:

    public class BradySkuza43
    {
        public static final String HIGH_SCORE_FILE = "coin-flip-score.txt";
    
        public static void main( String[] args ) throws Exception
        {
            final Scanner keyboard = new Scanner(System.in);
            final int highScore = getHighScore();
            final int newScore = getScore(keyboard);
    
            if(newScore != 0 && newScore > highScore){
                final String name = getName(keyboard);
                writeHighScore(name, newScore);
        }
    
        private static int highScore(){
            // read high score from high score file or return Integer.MIN_VALUE if 
            //    no high score file exists
        }
    
        private static int getScore(final Scanner keyboard){
            // play game, prompt user, get input, etc. and then 
            //   return the player's score.
        }
    
        private static String getName(final Scanner keyboard){
            // prompt the user for their name and return their input
        }
    
        private static void writeHighScore(final String name, final int score){
            // write this high score (with the name) to the high score file
        }
    
    }    
    

    当已有文件(具有“最佳”值)时,读取“最佳”的方式似乎不正确。您可能正在寻找类似这样的内容(根据您的数据进行修改)来读取“保存的最佳值”

            BufferedReader reader = new BufferedReader(new FileReader(in));
    
            String readNumber = "";
            while (reader.readLine() != null) {
                readNumber += reader.readLine();
            }
            best = Integer.valueOf(readNumber);
    

    最后不得不运行代码来查看保存文件是如何生成的。从文件(input.nextInt())的第二次读取中看到NoTouchElement异常就指出了问题所在

    如果你没有击败现有的连击(包括在第一次翻转时得到尾巴),你不会被提示输入名字。这会使保存文件被读取

    \n
    1
    \n
    
    默认情况下,扫描程序忽略空白。您不检查是否有可用的输入(hasNext方法)。当您在没有输入的情况下调用next()或nextInt()时,您将得到NoTouchElement。为什么会发生这种情况

    逐行:

    bestName = input.next();   <-- This is getting the "1" since there is a name saved
    best = input.nextInt();    <-- since the 1 was already read, so there's nothing to get
    

    如果出现问题,将停止代码运行,并停止添加一些调试语句以查看发生了什么

    这是因为您创建了一个文件,该文件可能最终为空(如果您没有获得高分),然后您尝试读取该空文件。您不应该创建高分文件,除非您真的要写入它。或者你应该处理一个空的高分文件。
    if(!foo.hasNext) { 
        System.out.println("foo should really have something here, but hasNext says it doesn't);
        System.exit();
    }