我正在创建HANGMAN游戏,其中有一个名为Keyboard的.txt文件,其内容如下:-
Q W E R T Y U I O P
A S D F G H J K L
Z X C V B N M
要打印此文件,我将使用常规方法进行打印:-
Scanner textScan = new Scanner(new File("src/Main/Keyboard"));
while(textScan.hasNextLine()) System.out.println(textScan.nextLine());
现在,每当用户输入字母(例如“ A”)时,我都希望编辑记事本,使其变为:-
Q W E R T Y U I O P
- S D F G H J K L
Z X C V B N M
依此类推。如何编辑此记事本,并在一轮后将其重置(即不带任何“-”)。
我使用IntelliJ IDEA 2018.1.6,我想知道如何清除输出窗口。在BlueJ中,
System.out.print("\f");
用于完成技巧。但是在这里,每次到达该行时都会出现箭头。
答案 0 :(得分:1)
看来我们在注释部分同意,为简单起见,应将文件扫描为字符串。第二部分可以通过递归和简单的String方法来解决。以下程序确实包含了您想要的所有内容,但它不是hangman的功能齐全的游戏,因此我将让您填补空白。
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class HangmanDriver {
public static final int mistakes_MAX = 6;
public static void main(String[] args) throws FileNotFoundException {
File myFile = new File("PATH TO YOUR KEYBOARD FILE");
String myText = "";
Scanner in = new Scanner(myFile);
while(in.hasNextLine()) {
myText += (in.nextLine() + "\n");
}
in.close();
String myWord = "";
boolean stillPlaying = true;
while(stillPlaying) {
in = new Scanner(System.in);
System.out.println("Enter the word for new game: ");
myWord = in.nextLine().toUpperCase();
playGame(in, false, 0, 0, myWord, myText);
System.out.println("Would you like to play again? [Y/N]");
char ans = in.next().charAt(0);
if(ans != 'y' && ans != 'Y')
stillPlaying = false;
}
System.out.println("Goodbye.");
}
public static void playGame(Scanner in, boolean isOver, int mistakes, int correct, String word, String text) {
if(isOver == false) {
System.out.println("\n" + text + "\n\nEnter a Letter (Must Be Upper Case)");
char letter = in.next().charAt(0);
if(text.indexOf(letter) != -1) {
text = text.replace(letter, '-');
if(word.indexOf(letter) != -1) {
for(char c : word.toCharArray()) {
if(letter == c)
correct++;
}
System.out.println("Good guess!");
if(correct == word.length()) {
System.out.println("You won!");
playGame(in, true, mistakes, correct, word, text);
} else {
playGame(in, false, mistakes, correct, word, text);
}
} else {
mistakes++;
System.out.println(mistakes_MAX-mistakes + " guesses left.");
if(mistakes == mistakes_MAX) {
System.out.println("Game Over!");
playGame(in, true, mistakes, correct, word, text);
} else {
playGame(in, false, mistakes, correct, word, text);
}
}
} else {
System.out.println("That is not an option. Try Again.\n\n");
playGame(in, false, mistakes, correct, word, text);
}
}
}
}