一次判断无法得出结果的就要使用开关
系统随机生成五个不同的大写字母的核心代码:
方法一:
package com.sun.xu;
import java.util.Random;
public class Generate {
public static void main(String[] args) {
char[] chs = new char[5];
char[] alp = { '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[] flag = new boolean[26];//开关
int index;
Random rand = new Random();
for (int i = 0; i < chs.length; i++) {
do {
index = rand.nextInt(26);
} while (flag[index] == true);
chs[i] = alp[index];
System.out.print(chs[i] + " ");
flag[index] = true;
}
}
}
方法二:
package com.sun.xu;
import java.util.Random;
public class Generate {
public static void main(String[] args) {
char[] chs = new char[5];
boolean[] flags = new boolean[26];
Random rand = new Random();
int index;
for (int i = 0; i < chs.length; i++) {
do {
index = rand.nextInt(26);
} while (flags[index] == true);
chs[i] = (char) (index + 65);
flags[index] = true;
System.out.print(chs[i] + " ");
}
}
}
检查玩家是否猜对了:
public static int[] check(char[] chs, char[] input) {
int[] result = new int[2];//result[0]保存猜对的个数,result[1]猜对的位置的个数
for (int i = 0; i < chs.length; i++) {
for (int j = 0; j < input.length; j++) {
if (chs[i] == input[j]) {
result[0]++;
if (i == j) {//位置正确
result[1]++;
}
break;
}
}
}
return result;
}