程序为什么就仅仅执行一个“游戏开始。。。”就不走了?到底是哪里错了?求解答
代码如下:
import java.util.Random;
import java.util.Scanner;
public class GuessChar {
public static void main(String[] args) {
int count = 0 ;//猜的次数
Scanner scan = new Scanner(System.in);
System.out.println("游戏开始...");
//1.生成随机数组
char[] chs = generate();
System.out.println("猜吧!");
while(true){
//接收用户收入的字符串
String str = scan.next().trim().toUpperCase();
if ("EXIT".equals(str)) {
break;
}
//将用户输入的字符串转化为数组
char[] input = str.toCharArray();
//对比判断
int[] result = check(chs, input);
//判断什么时候退出
if (result[0] == 5) {
int score = 5*100 - count*10;
System.out.println("恭喜你猜对了,总分"+score);
break;
}else {
System.out.println("没猜对,字符对"+result[1]+"个位置对"+result[0]+"个");
count++;
}
}
System.out.println("GuessChar>谢谢尝试,再见!");
scan.close();
}
//生成字符数组方法
//返回值为char[]:随机生成的字符数组
public static char[] generate(){
char chs[] = new char[5];
Random ran = new Random();
char[] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z' };
boolean[] flags = new boolean[letters.length];
for (int i = 0; i < chs.length; i++) {
int index;
do{
//生成0-25的数字
index = ran.nextInt(26);
}while(flags[index] = true);
//赋值
chs[i] = letters[index];
flags[index] = true;
}
return chs;
}
//判断猜测的结果
//chs:随机生成的字符数组
//input是用户输入的字符数组
//返回值类型int[]:猜的结果,猜对几个,位置对几个
public static int[] check(char[] chs,char[] input){
//arr[0]存字符对
//arr[1]存位置对
int arr[] = new int[2];//默认初值为0
//两层循环。用于判断字母和位置是否正确
for (int i = 0; i < chs.length; i++) { //控制随机的字符
for (int j = 0; j < input.length; j++) { //控制用户输入的字符
if (chs[i] == input[j]) {
arr[0]++; //字符对了所以++
if (i == j) {
arr[1]++;//位置对了 所以++
}
break;//此break只是跳出内层循环
}
}
}
return arr;
}
}
不提示编译错误 运行结果是