2016-04-14 47 views
0
char hangman[]; 
Scanner sc = new Scanner(System.in); 
Random r = new Random(); 
File input = new File("ComputerText.txt").useDelimiter(","); 
Scanner sc = new Scanner(input); 
String words; 

我想從一個.txt文件中讀取一組單詞,並讓程序選擇一個隨機單詞用於hang子手遊戲。如何讓Hangman Java文件從.txt文件中讀取隨機單詞?

下面的代碼適用於我們在代碼中讀取.txt文件的時候。 我們希望使用三個不同類別的.txt文件,每個文件都有不同的類別,並讓用戶選擇他們想要的單詞。

//while(decision==1){word=computerWord;} 
if (decision == 1) 
{ 
word=computerWord; 
} 
else if (decision == 2) 
{ 
word = countryWord; 
} 
else if (decision == 3) 
{ 
word = fruitWord; 
} 
else 
{ 
System.out.println("error, try again"); 
} 
+1

什麼不起作用?你遇到問題了嗎?也許創建一個readstream從文件中讀取? BufferedReader應該做的伎倆。 – Bram

+1

對不起Bram,我一直沒有用過java,只知道基礎知識。當我們將它們寫成如下形式時,主程序正在閱讀文字:String [] word = {「program」,「computer」,「download」,「database」};但我希望程序從文本文件中讀取這些文字,並使用隨機類來挑選文字 – sarahjane

+0

@sarahjane call sc.next(); – 2016-04-14 16:18:54

回答

0

下面是一個文件必須用掃描器類閱讀: -

try 
    { 
     Scanner input = new Scanner(System.in); 
     File file = new File("ComputerText.txt"); 

     input = new Scanner(file); 

     String contents; 
     while (input.hasNext()) 
     { 
      contents = input.next(); 
     } 
     input.close(); 

    } 
    catch (Exception ex) 
    { 
    } 

在這一點上的所有文件內容將在contetns變量,然後你可以使用split方法根據您的分隔符分割

0

你的方法應該是:

隨着進口如下:

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 

要使函數返回所需的字:

if (decision == 1) 
{ 
    word = getComputerWord(); 
} 
else if (decision == 2) 
{ 
    word = getCountryWord(); 
} 
else if (decision == 3) 
{ 
    word = getFruitWord(); 
} 
else 
{ 
    System.out.println("error, try again"); 
} 

實現下列方式:

public String getComputerWord() { 
    return getRandomWordFromFile(computerWordsPath); 
} 

public String getCountryWord() { 
    return getRandomWordFromFile(countryWordsPath); 
} 

public String getFruitWord() { 
    return getRandomWordFromFile(fruitWordsPath); 
} 

//returns random word from ","-delimited file of words 
public String getRandomWordFromFile(String path) { 
    String fileContent = readFileToString(path); 
    String[] words = fileContent.split(","); 
    Random rng = new Random(); 
    return words[rng.nextInt() % words.length]; 
} 


//build string from file by simply concatenating the lines 
public String readFileToString(String path) { 
    try { 
     BufferedReader br = new BufferedReader(new FileReader(path)); 

     try { 
      StringBuilder sb = new StringBuilder(); 
      String line = br.readLine(); 
      while (line != null) { 
       sb.append(line); 
       line = br.readLine(); 
      } 
      return sb.toString(); 
     } finally { 
      br.close(); 
     } 
    } catch (IOException ioe) { 
     //Error handling of malformed path 
     System.out.println(ioe.getMessage()); 
    } 
}