【发布时间】:2018-03-24 20:58:56
【问题描述】:
所以我的代码运行良好。我只需要限制猜测次数的帮助。而且每次你猜错了,都有一个计数器告诉你还剩多少个猜测。
所以我想将猜测的限制设置为 15。因此,每次您做出不正确的猜测时,错误的猜测计数器都会向用户显示(增加压力/压力)剩下 14 次猜测,否则您将失败。
这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Hangman {
private final static int maxGuesses = 5;
static ArrayList<String> words = new ArrayList<>();
static boolean isCorrect;
public static void main(String[] args) {
// getting file
File filename = new File("hangman.txt");
if (!filename.exists()) {
System.out.println(filename.getAbsolutePath());
System.out.println(filename + " does not exist.");
System.exit(1);
}
// reading word file
try {
Scanner input = new Scanner(filename);
while (input.hasNext()) {
words.add(input.next());
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
// debug: display words
//System.out.println(words);
Scanner input = new Scanner(System.in);
String playStats = "y";
while (playStats.equals("y")) {
String word = getWord();
String hiddenWord = getHiddenWord(word);
int missCount = 0;
while (true) {
System.out.print("(Guess) Enter a letter in word " + hiddenWord + " > ");
char ch = input.next().charAt(0);
if (!isAlreadyInWord(hiddenWord, ch)) {
hiddenWord = getGuess(word, hiddenWord, ch);
if (missCount>maxGuesses){
// Print info on max guesses reached
System.out.println("you have reached" + missCount + "you have" + maxGuesses +
" left");
break;
}
if(word.equals(hiddenWord)) {
if (!isCorrect) {
System.out.println(ch + " is not in the word.");
missCount++;
}
else {
System.out.println(ch + " is already in word.");
}
break;
}
}
}
System.out.println("The word is " + hiddenWord + " You missed " + missCount + " times");
System.out.println("Do you want to guess another word? Enter y or n >");
playStats = input.next();
}
}
public static String getWord() {
return words.get((int) (Math.random() * words.size()));
}
public static String getHiddenWord(String word) {
String hidden = "";
for (int i = 0; i < word.length(); i++) {
hidden += "*";
}
return hidden;
}
static public String getGuess(String word, String hiddenWord, char ch) {
isCorrect = false;
StringBuilder s = new StringBuilder(hiddenWord);
for (int i = 0; i < word.length(); i++) {
if (ch == word.charAt(i) && s.charAt(i) == '*') {
isCorrect = true;
s = s.deleteCharAt(i);
s = s.insert(i, ch);
}
}
return s.toString();
}
public static boolean isAlreadyInWord(String hiddenWord, char ch) {
for (int i = 0; i < hiddenWord.length(); i++) {
if (ch == hiddenWord.charAt(i)) {
return true;
}
}
return false;
}
}
我假设它与我作为计数器的“missCount”有关....但是我如何在其中写下 missCount 不能超过 15 次尝试并显示尝试次数?
提前致谢。
【问题讨论】:
-
我对这个问题投了反对票,因为这里的代码太多了。为了明确您的问题出在哪里,请删除任何不直接导致您的问题的代码,如果您可以将其减少到十行或更少,我将考虑撤回反对票。请参阅:How to create a Minimal, Complete, and Verifiable example 和 How to Debug Small Programs
-
@Joe C 投反对票。你没有看我的问题。没有问题。我特别指出我的代码正在运行。
标签: java exception-handling counter