[Java] 纯文本查看 复制代码
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void main(String[] args){
String[] words = {"a", "my", "tom", "help", "black"};
Scanner input = new Scanner(System.in);
boolean again = true;
while(again) {
String[] guessWord = getGuessWord(words);
String[] finalGuess = new String[guessWord.length];
Arrays.fill(finalGuess, "*");
int counts = 0;
String[] fG = new String[guessWord.length];
Arrays.fill(fG, "*");
do {
int[] c = {0};
System.out.print("(guess) enter a letter in word ");
for(int i = 0; i < guessWord.length; i++) {
System.out.print(finalGuess);
}
System.out.print(" > ");
String youGuess = input.next();
fG = guess(youGuess, guessWord, fG, c);
int i = 1;
if(Arrays.equals(fG, finalGuess) && (c[0] != i)) {
System.out.println(youGuess + " is not in the word");
counts++;
}
System.arraycopy(fG, 0, finalGuess, 0, fG.length);
}while(isRight(finalGuess, guessWord));
char[] finalGuessChar = new char[finalGuess.length];
for(int i = 0; i < finalGuess.length; i++) {
finalGuessChar = finalGuess.charAt(0);
}
System.out.print("the word is ");
System.out.print(finalGuessChar);
System.out.println(". " + "you missed " + counts + " time");
System.out.println("do you want to guess another word? enter y or n>");
String enter = input.next();
if(enter.toUpperCase().equals("Y")) {
again = true;
}else {
again = false;
System.out.println("byebye");
}
}
}
public static String[] getGuessWord(String[] words) {
String word = words[(int)(Math.random() * words.length)];
String[] charr = new String[word.length()];
for(int i = 0; i < word.length(); i++) {
charr = word.charAt(i) + "";
}
return charr;
}
public static String[] guess(String ch, String[] word, String[] fG, int[] c) {
for(int i = 0; i < word.length; i++) {
if(ch.equals(fG)) {
System.out.println(ch + " is already in the word");
c[0]++;
break;
}
if(ch.equals(word)) {
fG = ch;
}
}
return fG;
}
public static boolean isRight(String[] f, String[] g) {
boolean yon = Arrays.equals(f, g);
return !yon;
}
}