1.(遊戲:猜字遊戲)
編寫一個猜字遊戲。隨機產生一個單詞,提示用戶一次猜測一個字母,如運行示例所示。單詞中的每個字母顯示爲一個星號。當用戶猜測正確後,正確的字母顯示出來。當用戶猜出一個單詞,顯示猜錯的次數,並且詢問用戶是否繼續對另外一個單詞進行遊戲。聲明一個數組來存儲單詞,如下所示:
問題分析:首先我們先創建一個題庫,然後隨機抽取一個單詞,然後加密,*號的長度爲抽取單詞的長度。
玩家開始遊戲時輸入字符,我們創建一個方法來判斷是否猜對,如果猜對則在該位置打印該字母,猜錯的話加密程度不變,猜錯次數+1。如果全部猜對,打印該單詞及猜錯次數,並且詢問玩家是否繼續。
代碼實現:
import java.util.*;
class Demo{
//1.創建一個詞庫
private static String words[]={"one","two","three"};
//2.抽取一個詞
private static String word=null;
//3.該單詞被猜出來的程度
private static boolean[] state=null;
//4.你猜錯的次數
private static int missed =0;
public static void main(String[] args) {
Random random=new Random();
Scanner scanner=new Scanner(System.in);
word=words[random.nextInt(words.length)];
state=new boolean[word.length()];
//5.開始猜單詞
while(true){
String pwd=getPwd();
System.out.print("Enter a letter in word "+pwd+":");
String letter =scanner.next();
changeWordState(letter);
if(isEnd()){
//一輪遊戲結束,是否繼續
System.out.println("The word is "+word+".You missed "+missed+(missed>1?" times":" time"));
System.out.print("Do you want to guess another word?Enter yes or other:");
if(scanner.next().equals("yes")){
word=words[random.nextInt(words.length)];
state=new boolean[word.length()];
missed=0;
}else{
break;
}
}
}
}
private static boolean isEnd(){
for(int i=0;i<state.length;i++){
if(state[i]==false){
return false;
}
}
return true;
}
private static void changeWordState(String letter){
//進行猜詞,猜對在對應位置打印,猜錯不改變打印且猜錯次數+1
boolean flag =false;
for(int i=0;i<word.length();i++){
if((word.charAt(i)+"").equals(letter)){
flag=true;
if(state[i]==false){
state[i]=true;
}else{
System.out.println("/t"+letter+" is already in the word");
return;
}
}
}
if(!flag){
missed++;
System.out.println("\t"+letter+" is not in the word");
}
}
private static String getPwd(){
//創建密文,取隨機單詞的長度,打印*
String pwd="";
for(int i=0;i<word.length();i++){
if(state[i]==true){
pwd+=word.charAt(i);
}else{
pwd+="*";
}
}
return pwd;
}
}