Я пытаюсь сделать какую-то «игру с злым вешалкой» (отличные упражнения Стэнфордского CS). Цель игры - «обмануть», удалив как можно больше возможных текстовых решений, чтобы пользователь не мог догадаться до самого конца.Java - сканер не удаляет все нужные объекты
Я сделал петлю (ниже), которая, кажется, удаляет многие слова возможных слов, но по какой-то причине она не удаляет их всех. Вход представляет собой файл dictionary.txt, который содержит около 120 тыс. Слов.
Когда я догадываюсь, «буква« а »это займет около 60-70% слов с« а »в них (оценка основана на сравнении между выходом с первой парой слов в файле txt)
File file = new File("dictionary.txt");
Scanner textScan = new Scanner(file);
List<String> wordList = new ArrayList<String>();
while (textScan.hasNext())
{
word = textScan.next();
wordList.add(word);
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
Scanner textScan1 = new Scanner(file);
for(int i = 0; i <= guessNumber; i++)
{
Collections.sort(wordList);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
guess = guess.toLowerCase();
while (textScan1.hasNext())
{
String word1 = textScan1.next();
if (wordLength != word1.length() && word1.contains(guess))
{
wordList.remove(word1);
}
}
}
Я знаю, что мой код немного грязный в этот момент, я пытаюсь улучшить все о моем программировании, так что все отзывы очень ценятся! У меня такое чувство, что я включаю вещи, которые не обязательно должны быть там и так далее.
Я буду размещать весь код, в случае, который помогает:
import java.util.*;
import java.lang.*;
import java.io.*;
public class EvilHangman
{
public static void main(String[] args) throws IOException
{
// declaring variables
int wordLength;
int guessNumber;
// initiate the scanner
Scanner keyboard = new Scanner(System.in);
// introduction and prompting 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();
}
// count the number of words with the specified length
/* int wordCount = 0;
String word = null;
while (textScan.hasNext())
{
word = textScan.next();
if (word.length() == wordLength)
{
wordCount++;
}
}
*/
// prompts the user whether he/she wants a running count of word length - using next() instead of nextLine() to clear buffer
/* System.out.println("Do you want a running total of number of words remaining? ");
String runningTotal = keyboard.next();
if (runningTotal.equalsIgnoreCase("yes"))
System.out.println("Words with that length: " + wordCount);
*/
// create a list (array) of all the words that matches the input length
String word = null;
File file = new File("dictionary.txt");
Scanner textScan = new Scanner(file);
List<String> wordList = new ArrayList<String>();
while (textScan.hasNext())
{
word = textScan.next();
wordList.add(word);
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
Scanner textScan1 = new Scanner(file);
for(int i = 0; i <= guessNumber; i++)
{
Collections.sort(wordList);
System.out.println("Type in your guess as a letter ");
String guess = keyboard.next();
guess = guess.toLowerCase();
while (textScan1.hasNext())
{
String word1 = textScan1.next();
if (wordLength != word1.length() && word1.contains(guess))
{
wordList.remove(word1);
}
}
}
System.out.println("The ArrayList has " + wordList.size() + " objects stored in it.");
System.out.println(wordList);
Все слова в словаре нижнего регистра? Если это так, эта строка 'guess = guess.toLowerCase();' может быть проблема, поскольку вы проверяете только строчные буквы. –