2014-11-04 106 views
0

我正在創建一個硬幣翻轉游戲,以保存您最後的高分和名字。該程序工作正常,如果沒有高分的文件已經存在,但如果有文件在那裏程序停止工作。硬幣翻轉游戲保存問題

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錯誤。我假設它與導入功能有關,但我不知道如何解決它。

+1

這是因爲您創建的文件最終可能爲空(如果您沒有得到高分),然後嘗試從該空文件讀取。除非您真的要寫入高分文件,否則不應創建高分文件。或者你應該處理一個空的高分檔案。 – Jared 2014-11-04 06:01:03

回答

0

以下是一些建議:

  1. 你的高分文件的名稱不會改變,對不對?它不應該是一個變量,它應該是一個static final變量。
  2. 玩遊戲和然後決定這是否是一個高分。所以你應該有一個getHighScore()方法(可以是static)。
  3. 如果得分是高分,則將其寫入高分檔案。應該有一個方法static writeHighScore(final String name, final int score)

所以我想你的程序改變的東西更是這樣的:

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 
    } 

}  
1

你讀「最好」的方式,當已經有一個文件(「最好」的值)似乎是不正確。您可能正在尋找這樣的內容(根據您的數據進行修改)來讀取「保存的最佳值」。

 BufferedReader reader = new BufferedReader(new FileReader(in)); 

     String readNumber = ""; 
     while (reader.readLine() != null) { 
      readNumber += reader.readLine(); 
     } 
     best = Integer.valueOf(readNumber); 
1

結束了不得不運行代碼,看看如何生成保存文件。看到NoSuchElement異常來自指向該問題的文件(input.nextInt())的第二次讀取。

如果您沒有擊敗現有連勝(包括將TAILS作爲第一次翻球),則不會提示您輸入姓名。這使得保存文件讀取

\n 
1 
\n 

掃描儀默認情況下忽略空白。你不檢查是否有可用的輸入(hasNext方法)。如果在沒有輸入時調用next()或nextInt(),則獲得NoSuchElement。爲什麼這是從保存中發生的?

逐行:

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 

,隨着越來越初始TAILS後SAVEFILE第二輸入,導致您的崩潰。

兩種解決方案,確保你正在和你的主要結束在其他保存bestName,或在閱讀SAVEFILE更加小心。

(編輯) 一般使用掃描儀(或者是任何的API,它具有的hasNext()/下一個()的方式)時,最好之前,每個下調用和檢查hasNext()()。這將確保你從下一個()獲得一些東西。

即使你不覺得是有可能的原因有沒有被什麼東西在那裏,有類似

if(!foo.hasNext) { 
    System.out.println("foo should really have something here, but hasNext says it doesn't); 
    System.exit(); 
} 

將停止你的代碼在其軌道上,如果有問題,給你停止添加一些調試語句來查看發生了什麼。