java - 陷入Java电影猜谜游戏的逻辑(通过udacity)
问题描述
我正在Java上制作一个电影猜谜游戏(很像刽子手,但不包含简笔画之类的东西),它逐个字母地从用户那里获取输入。我被困在我想要输入的字母以替换电影标题中该字母的所有实例的位置。我的代码没有完全工作。稍后,我将应用阻止用户再次输入相同字母的逻辑。但目前我需要解决这个特定问题。有什么帮助吗?
这是我的游戏类中的游戏过程函数。
public void GameProcess(char[] dashedarray) {
Scanner input = new Scanner(System.in);
char guess;
int i = 0;
int spaces = 0;
int correct = 0;
int wrong = 0;
boolean run = true;
while (run) {
if (dashedarray[i] == ' ') {
spaces++;
i++;
continue;
} else {
System.out.println("Enter your guess.");
guess = input.next().charAt(0);
for (int j = 0; j < dashedarray.length; j++) {
if (dashedarray[j] != ' ') {
if (moviename.charAt(i) == guess) {
dashedarray[i] = guess;
correct++;
}
else if(moviename.charAt(j) == guess) {
dashedarray[j] = guess;
correct++;
}
}
else
{
wrong++;
}
}
i++;
PrintArray(dashedarray);
if (correct == (moviename.length() - spaces)) {
System.out.println("You have won.");
break;
} else if (wrong == 10) {
System.out.println("You have lost.");
break;
}
System.out.println("The number of wrong guesses is " + wrong + ".");
}
}
解决方案
你根本不需要i
。spaces
就是统计你的答案有多少个空格,这个不用猜。您应该在循环之外执行此操作。
Scanner input = new Scanner(System.in);
char guess;
int i = 0;
int spaces = 0;
int correct = 0;
int wrong = 0;
boolean run = true;
for (int i = 0; i < dashedarray.length; i++) {
spaces++;
}
while (run) {
System.out.println("Enter your guess.");
guess = input.next().charAt(0);
boolean match = false;
for (int j = 0; j < dashedarray.length; j++) {
if (dashedarray[j] != ' ') {
if(moviename.charAt(j) == guess) {
dashedarray[j] = guess;
correct++;
match = true;
}
}
}
// It matched nothing, this input is wrong.
if (!match) {
wrong++;
}
PrintArray(dashedarray);
if (correct == (moviename.length() - spaces)) {
System.out.println("You have won.");
break;
} else if (wrong == 10) {
System.out.println("You have lost.");
break;
}
System.out.println("The number of wrong guesses is " + wrong + ".");
}
推荐阅读
- php - 在 PHP 中调用 API GET 请求后没有响应
- python - 来自谷歌云视觉响应nodejs的非最大抑制
- reactjs - 如何在此处定义 proptypes
- r - 由于另一个数据,如何对向量的元素进行排序?
- java - Java - JProgressBar 不会改变值,而 JLabel 不会改变文本
- python - 在 python Django 中从自定义 gsuit 域安全地发送电子邮件
- javascript - node-cron:等待作业完成执行下一个
- python-3.x - 除了 OSError 错误外,我无法设置异常尝试:使用 python3 在 Exscript 中超时
- laravel - 我正在尝试使用 Laravel 作业类在队列中发送电子邮件,但它只是一直说找不到类
- angular - 从路由器加载 URL 以在 NgModule 中使用