我正在創建一個硬幣翻轉游戲,以保存您最後的高分和名字。該程序工作正常,如果沒有高分的文件已經存在,但如果有文件在那裏程序停止工作。硬幣翻轉游戲保存問題
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();
}
}
當有文件已經存在時,我得到一個NoSuchElement錯誤。我假設它與導入功能有關,但我不知道如何解決它。
這是因爲您創建的文件最終可能爲空(如果您沒有得到高分),然後嘗試從該空文件讀取。除非您真的要寫入高分文件,否則不應創建高分文件。或者你應該處理一個空的高分檔案。 – Jared 2014-11-04 06:01:03