编写一个猜单词的程序,实现将预定的“Java,Python,Wellcome,Study,Student",随机抽取1个,并提示首字母和总长度,供用户猜。要求如下: (I)若猜对了,则退出,否则,提示第几位错了,直到猜对为止。 (2)使用String类的length()、charAt()、equals()或compareTo()方法。
时间: 2024-03-05 13:49:21 浏览: 18
好的,让我来为您编写这个猜单词的程序:
```java
import java.util.Random;
import java.util.Scanner;
public class GuessWord {
public static void main(String[] args) {
String[] words = {"Java", "Python", "Wellcome", "Study", "Student"};
Random random = new Random();
int index = random.nextInt(words.length);
String word = words[index];
int length = word.length();
char firstChar = word.charAt(0);
System.out.println("单词的首字母是:" + firstChar);
System.out.println("单词的长度是:" + length);
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("请猜一个单词:");
String guess = scanner.nextLine();
if (guess.equals(word)) {
System.out.println("恭喜你,猜对了!");
break;
} else {
int count = 0;
for (int i = 0; i < length; i++) {
if (guess.charAt(i) != word.charAt(i)) {
count++;
}
}
System.out.println("你猜错了,第" + (count + 1) + "个字母不对!");
}
}
}
}
```
程序的思路如下:
1. 定义一个字符串数组,包含预设的单词;
2. 生成一个随机数,随机抽取一个单词;
3. 获取单词的长度和首字母,并输出提示信息;
4. 使用循环进行猜词,如果猜对了,则退出循环并输出恭喜信息;如果猜错了,则输出错误信息,继续循环猜词。
在比较猜测的单词和预设的单词是否相等时,使用了String类的equals()方法;在比较每个字母是否相等时,使用了charAt()方法。