2015-04-24 31 views
3

我目前正在構建文本冒險遊戲,並且在嘗試讀取包含房間描述的文本文件時遇到問題。每當我運行該程序,我可以正確讀取並指定第一個文本文件,但第二個引發以下錯誤......NoSuchElementException:在文本文件中讀取文本時發現沒有行

Exception in thread "main" java.util.NoSuchElementException: No line found 
    at java.util.Scanner.nextLine(Scanner.java:1540) 
    at Input.getInput(Input.java:9) 
    at Room.buildRoom(Room.java:92) 
    at Main.main(Main.java:19) 

我不能肯定是什麼原因造成這一點。我嘗試過移動東西,但無濟於事。以下是我打電話給房間對象本身分配所有信息的功能。

public void buildRoom(int num, String name, Room north, 
     Room south, Room east, Room west) throws FileNotFoundException { 
    System.out 
      .println("Please input the location of the file you'd like to read in. Please note that you must read in the files in numerical order, or your game will not work."); 

    String input = Input.getInput(); 

    File file = new File(input); 
    Scanner reader = new Scanner(file); 

    String description = reader.next(); 
    this.setDescription(description); 

    this.setNorthExit(north); 
    this.setSouthExit(south); 
    this.setEastExit(east); 
    this.setWestExit(west); 
    reader.close(); 
} 

任何幫助搞清楚爲什麼會發生這將不勝感激。如果您有任何問題,請隨時提問,我會盡我所能回答。

編輯:輸入功能如下...

public static String getInput() { 

    System.out.print("> "); 
    Scanner in = new Scanner(System.in); 
    String input = in.nextLine(); 
    input.toLowerCase(); 
    in.close(); 
    return input; 
} 
+0

那麼你在哪裏提供從中讀取數據的文件名? –

+0

我們可以看到「輸入」是什麼以及它是如何創建的? – Tdorno

+0

@Tdorno:是的。我也想知道'Input'。 –

回答

1

不要讓每次調用getInput方法時關閉STD輸入。 Scanner::close關閉基礎流。

在外面創建Scanner並繼續使用它。將它創建到某個地方,直到您最後一次致電getInput

Scanner對象傳遞給getInput方法。

Scanner sc = new Scanner(System.in); 
while(whatever) 
{ 
    String s = getInput(sc); 
    .... 

} 
sc.close(); 

public static String getInput(Scanner in) 
{ 
    System.out.print("> "); 
    String input = in.nextLine(); 
    input.toLowerCase(); 
    return input; 
} 
+0

謝謝!這似乎已經做到了。 – Starchild192