51,407
社区成员
发帖
与我相关
我的任务
分享要求猜五个大写字母,每次猜完提示猜对字母的数量,和猜对字母位置的数量
public class HomeWork {
public static void main(String[] args) {
String str = "ASDFG";//用来储存5个字符
/* for (int i = 0; i < 5; i++) {
int machine = (int) (Math.random() * 26 + 65);
char a = (char) machine;
str += a;
}*/
//随机数产生5个字符储存在str中,
// 暂时不用,先用确定的答案ASDFG来检验程序
int num = 0;//统计数量正确
int numLocation = 0;//统计位置正确
int count=0;//统计猜的次数
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入5个大写字母:");
String guess = sc.next();
count++;
for (int i = 0; i < 5; i++) {
//得到数量正确的有几个
for (int j = 0; j < 5; j++) {
if (guess.charAt(i) == str.charAt(j)) {
num++;
break ;
//如果有guess中已经等于答案中的某一个位置了,就打断本次循环,避免答案为AASDF时,将猜的一个A的算两遍。
!!!问题也出现在这,这只能解决答案有重复的情况,不能解决猜的字母重复,如果猜AAQWE,时如果答案是ASDFG,num也会加两遍
}
}
//得到位置正确的有几个
if (guess.charAt(i) == str.charAt(i)) {
numLocation++;
}
}
//当位置正确的有5个时,跳出循环
if(numLocation==5) {
System.out.println("猜对了,你的得分"+(500-count*10));
break;
}
System.out.println("GuessGame>你猜对了" + num +
"个,位置有" + numLocation + "是对的。总次数="+count+"次");
num=0;
numLocation=0;
}
}
我运行的结果和你不一样 num = 1

猜字母游戏本来就不能出现重复字母好不。这就是猜数字的复杂玩法而已