Java 猜詞游戲
1.1題目說明
隨機產生一個單詞,提示用戶每次猜一個字母,單詞中的每個字母以星號顯示,當用戶 猜對一個字母時,顯示實際字母,當用戶完成一個單詞時,顯示猜錯的次數,同時詢問用戶是否繼續下一單詞,單詞存盤使用陣列形式,如:String[] words = {“write”,”that”,…};
1.2 分析程序
? 用戶開始,使用chooseWord()在定義的字串陣列中隨機產生一個單詞,使用名為label的char型別的陣列,里面的每個字母設定為*,然后用戶進行猜測,一共有七次猜測的機會,每進行一次猜測,如果猜測成功,則輸出該字母在單詞中的位置,否則輸出該字母沒有在單詞中,如果在猜測七次中,猜對該單詞,則退出for回圈,輸出單詞和用戶猜錯的次數,如果七次結束之后沒有猜測出該單詞,則輸出猜錯七次,然后詢問用戶是否進行下一局,如果用戶輸入y,則回傳重新開始游戲,如果用戶輸入n,則結束游戲,
相關函式:chooseWord():在定義的字串陣列中隨機產生一個字串
1.3 系統測驗

1.4代碼展示
package version1;
import java.util.Random;
import java.util.Scanner;
/**
* @Auther: paradise
* @Date: 2021/6/24 - 06 - 24 - 16:19
*/
public class Guess {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] words = {"write", "that", "pearson", "animal", "program", "intro"};
while (true) {
String word = chooseWord(words);
int count = 0;
//label是星號的表示方法
char[] label = new char[word.length()];
for (int i = 0; i < word.length(); i++) {
label[i] = '*';
}
//用戶允許輸入7次
for (int i = 0; i < 7; i++) {
System.out.print("Enter a letter in the word ");
for (int j = 0; j < label.length; j++) {
System.out.print(label[j]);
}
System.out.print(":");
String letter = input.next();
char firstChar = letter.charAt(0);
if (word.indexOf(firstChar) != -1) {
for (int j = 0; j < word.length(); j++) {
if(firstChar == word.charAt(j))
label[j] = firstChar;
}
} else {
System.out.println(firstChar + " is not in the word");
count++;
}
//如果猜的已經和原單詞一樣了,那么退出此回圈
String newString = new String(label);
if(newString.equals(word))
break;
}
System.out.println("The word is " + word + ".You missed " + count + " times.");
System.out.println("Do you want to guess for another word? Enter y or n");
String s = input.next();
if (s.equals("y")) {
continue;
}
else if (s.equals("n")) {
break;
}else {//非法輸入退出
System.out.println("無效輸入");
System.exit(0);
}
}
}
//選擇陣列中一個元素的方法
public static String chooseWord(String[] s){
Random random = new Random();
int n = random.nextInt(s.length);
String word = s[n];
return word;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394075.html
標籤:其他
上一篇:Python中的正則運算式根據以@開頭并以:結尾的字符拆分字串?
下一篇:c# 搜索目錄中某些檔案
