[英]How do I get my Hangman Java file to read a random word in from a .txt file?
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文件中讀取一組單詞,並讓程序選擇一個在hangman游戲中使用的隨機單詞。
下面的代碼用於當我們在代碼中讀取.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");
}
這是必須使用掃描儀類讀取文件的方式:-
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方法根據您的分度符進行拆分
您的方法應該是:
具有以下進口:
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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.