public class guessword {
public static void main(String[] args) {
String[] words = {"apple","banana","cherry","orange","pear","watermelon","pitaya","mango","coconut"};
//定義數組為題庫
Random random = new Random();
int windex = random.nextInt(words.length);
//產生隨機數組下標
String guessword = words[windex];
//產生被猜的單詞
System.out.println(guessword);
//輸出被猜寫的單詞
String[] word = new String[words[windex].length()];
//把被猜寫的單詞轉成字符串數組
for (int i = 0; i <word.length;i++){
word[i] = "-";
}
//遍歷數組,把數組中的字符串替換成等長度的“-”
for (int i = 0; i < word.length;i++){
System.out.print( word[i]+" ");
}
//輸出與被猜寫單詞等長度的“-”
int guesscount = 5;
//設置猜單詞次數
System.out.println();
//換行
while (true){
Scanner scanner = new Scanner(System.in);
String zm = scanner.next();
//接受用戶輸出字母
int num = 0;
if (guessword.indexOf(zm) >= 0){
while (true){
num = guessword.indexOf(zm,num);
//定義 輸入字母 在被猜寫單詞中的 起始 查找下標
if (num >= 0){
word[num] = zm;
num++;
//找到并替換“-”
}
else {
break;
}
}
for (int i = 0; i < word.length;i++){
System.out.print( word[i]+" ");
//輸出當前查找情況
}
System.out.println();
//換行
}else {
guesscount--; // 輸入的字母不在被猜單詞內,猜單詞次數減一
if (guesscount == 0){
System.out.println("你輸了,游戲結束"); //如果猜單詞次數等于0 游戲結束 你輸了 跳出循環
break;
}
System.out.println("錯了,還有"+guesscount+"次錯的機會"); //輸出剩余猜單詞次數
}
boolean isfind = false; //布爾變量 判斷 被猜寫單詞中是否還存在“-”
for (int i = 0; i < word.length;i++){
if (word[i].equals("-")){
isfind = true; // 如果還存在繼續猜
break;
}
}
if (isfind == false){
System.out.println("你贏了"); //如果不存在 游戲結束 你贏了
}
}
}
}
我的猜單詞
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
- 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
- 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...