Java - 读取/扫描文本文件的字符串长度并在程序中使用它

时间:2013-03-12 05:24:17

标签: java string file search

我正在尝试用Java创建一个简单的hangman游戏。我有一个名为dictionary.txt的文本文件,其中包含来自英语词典的120K单词。当我要提示用户输入单词长度并显示具有该特定长度的单词数时,就会出现问题。

在这里度过了相当长的一段时间后谷歌搜索我已经走了这么远,但现在我被卡住了:

import java.util.Scanner;
import java.io.*;
import java.io.IOException;



public class Hangman 

{


public static void main(String[] args) throws IOException
{
    // declaring variables
    int wordLength;
    int guessNumber;


    // initiate the scanner
    Scanner keyboard = new Scanner( System.in );

    // read the dictionary file 

    File file = new File("dictionary.txt");
    StringBuilder contents = new StringBuilder();
    BufferedReader reader = null;



    // prompt the user for word length

    System.out.println("Welcome to Hangman. Let's play! ");
    System.out.println("Please enter the desired word length: ");
    wordLength = keyboard.nextInt();

    while(wordLength < 0 || wordLength > 26)
    {
        System.out.println("This is not a valid word length. ");
        System.out.println("Please enter the desired word length: ");
        wordLength = keyboard.nextInt();
    }

    // prompt the user for number of guesses 

    System.out.println("How many guesses do you want to have? ");
    guessNumber = keyboard.nextInt();

    while(guessNumber < 0)
    {
        System.out.println("Number of guesses has to be a postive integer. ");
        System.out.println("Please enter the desired number of guesses: ");
        guessNumber = keyboard.nextInt();
    }




    }

}

我的目标是提示用户输入一个字长,如果在dictionary.txt文件中不存在所需的字长,那么它会一直询问,直到给出有效的答案。

我还希望能够打印出具有给定单词长度的单词数量(例如,如果用户输入&#34; 10&#34 ;,那么它会显示在dictionary.txt中有多少单词具有10个字母的长度。

代码的以下部分是我希望用读取txt文件并在其后执行的代码替换的部分:

while(wordLength < 0 || wordLength > 26)
{
    System.out.println("This is not a valid word length. ");
    System.out.println("Please enter the desired word length: ");
    wordLength = keyboard.nextInt();
}

我可能采取了错误的方法,所以非常欢迎所有反馈!

2 个答案:

答案 0 :(得分:1)

此代码可用于建立每个字长的字数。

// map where the key is the length of a word and
// the value is the number of words of that length
Map<Integer, Integer> numberOfWordsOfLength = new HashMap<>();

Scanner dictionaryScanner = new Scanner(file);

while (dictionaryScanner.hasNext())
{
   String word = dictionaryScanner.next();
   int wordLength = word.length();
   numberOfWordsOfLength.put(wordLength, 1 +
      numberOfWordsOfLength.containsKey(wordLength) ?
      numberOfWordsOfLength.get(wordLength) :
      0);
}

然后,当你想知道是否有任何给定长度的单词时,你可以使用它。

numberOfWordsOfLength.containsKey(length)

如果你想获得字典中具有给定长度的单词数量,你可以使用它。

numberOfWordsOfLength.get(length)

稍后,当您想要选择给定长度的随机单词时,您可以执行以下操作。

int wordIndex = new Random().nextInt(numberOfWordsOfLength.get(length));
Scanner dictionaryScanner = new Scanner(file);
String word;
while (dictionaryScanner.hasNext())
{
   String candidateWord = dictionaryScanner.next();
   if (candidateWord.length() != length) continue;
   if (wordIndex == 0)
   {
      word = candidateWord;
      break;
   }
   --wordIndex;
}

答案 1 :(得分:0)

试试这个:

try
{
    Scanner input = new Scanner(file);
    boolean flag = true;
    while(flag)
    {
        ArrayList<String> words = new ArrayList<String>(120000);
        while(input.hasNextLine())
        {
            String s = in.nextLine();
            if(s.length() == wordLength)
            {
                words.add(s);
            }
        }
        if(words.isEmpty())
        {
            System.err.print("Invalid word length, please try again\n>");
            wordLength = keyboard.nextInt();
        }
        else
        {
            flag = false;
            System.out.println("There were " + words.size() + " such words");
        }
    }
}
catch(Exception e)
{
    e.printStackTrace();
}

有效吗?