最好将您需要做的事情分解成更小的步骤:
- 从一号玩家那里得到10个字
- 对于每个单词,使用该单词玩一轮游戏
让我们将这些步骤命名为 getWords 和 playRound
从第一步开始,我们想要得到一个包含 10 个单词的列表:为此,我们可以使用 List<String>
让我们为它创建一个方法:
private static List<String> getWords( int numberOfWords )
{
Scanner s = new Scanner( System.in );
List<String> words = new ArrayList<String>();
for ( int i = 0; i < numberOfWords; i++ )
{
words.add( s.nextLine() );
}
return words;
}
现在我们可以调用这个方法来获取我们的单词列表,并将它们一次一个单词提供给我们的第二个方法:
public static void main( String[] args )
{
int numberOfWords = 10;
System.out.println( "Player 1: enter " + numberOfWords + " words" );
List<String> words = getWords( numberOfWords )
System.out.println( "Ready, player 2?" );
for ( String word : words )
{
playRound( word );
}
}
所以现在我们有一个更简单的问题——打一个回合,它涉及以下步骤:
- 选择三个我们要屏蔽字母的位置
- 创建一个单词的蒙版版本,其中选定的字母被划掉,并将其显示给玩家二
- 玩家二猜一个字母:
- 猜对了吗?如果是这样,请将相应的破折号替换为该字母
- 从第 3 步开始重复,直到所有破折号消失
让我们将前三个步骤命名为方法:
private static List<Integer> getMaskPositions( String word ) { ... }
private static StringBuilder createdMaskedWord( String word, List<Integer> maskPositions ) { ... }
private static char getNextGuess( ) { ... }
然后我们可以在playRound() 方法中使用这些:
private static void playRound( String word )
{
// choose three positions to mask out:
List<Integer> maskPositions = getMaskPositions( word );
// mask our word by dashing out the three chosen positions:
StringBuilder maskedWord = createdMaskedWord( word, maskPositions );
System.out.println( "The next word is: " + maskedWord );
while ( maskedWord.toString().contains( "-" ) )
{
// fetch a one-character guess from Player 2:
char guess = getNextGuess();
for ( Integer position : maskPositions )
{
if ( word.charAt( position ) == guess )
{
// guess is correct: replace the dash with the right letter
maskedWord.setCharAt( position, guess );
}
}
// now re-display the masked word (showing any correctly-guessed letters):
System.out.println( maskedWord );
}
// no more dashes left: all missing letters correctly guessed:
System.out.println( "Well Done!" );
}
这仍然需要实现三个方法:getMaskPositions()、createdMaskedWord() 和 getNextGuess(),但现在这些已经很多了更简单的问题供您解决(并且您可以重复使用您已经编写的一些代码)。
请注意,我们使用 StringBuilder 来存储 maskedWord:这允许我们更改字母(不能使用不可变的 String 进行此操作)。
您还可以通过检查有效输入来改进我的代码:例如,每个单词不得短于 3 个字母。
剩下的交给你:)