【题目要求】
【步骤】
//1.先生成一组单词
public static String[] words={“big”,“small”,“long”,“short”};
//2.随机抽取一个单词
public static String word=null;
//3.创建该单词的一个状态数组
public static boolean[] state=null;
//4.当前轮猜错的次数
public static int missed=0;
【代码实现】
import java.util.*;
class Class34{
//1.先生成一组单词
public static String[] words={"big","small","long","short"};
//2.随机抽取一个单词
public static String word=null;
//3.创建该单词的一个状态数组
public static boolean[] state=null;
//4.当前轮猜错的次数
public static int missed=0;
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
Random random=new Random();
word=words[random.nextInt(words.length)];
state=new boolean[word.length()];
//5.开始输入字符猜单词
while(true){
String password=getPassWord();
System.out.print("Enter a letter in word "+password+":");
String letter=scanner.nextLine();
changeWordState(letter);
if(isEnd()){
System.out.println("The word is "+word+".You missed "+missed+" time");
System.out.print("Do you want to guess another word?Enter y or n:");
if(scanner.nextLine().equals("y")){
word=words[random.nextInt(words.length)];
state=new boolean[word.length()];
missed=0;
}else{
break;
}
}
}
}
//判断一轮是否结束
public static boolean isEnd(){
for(int i=0;i<state.length;i++){
if(state[i]==false){
return false;
}
}
return true;
}
//改变单词状态
public static void changeWordState(String letter){
boolean isExist=false;
for(int i=0;i<word.length();i++){
if((word.charAt(i)+"").equals(letter)){
isExist=true;
if(state[i]==false){
state[i]=true;
}else{
System.out.println("\t"+letter+" is already in the word");
return;
}
}
}
if(!isExist){
missed++;
System.out.println("\t"+letter+" is not in the word");
}
}
public static String getPassWord(){
String password="";
for(int i=0;i<word.length();i++){
if(state[i]==true){
password+=word.charAt(i);
}else{
password+="*";
}
}
return password;
}
}