我已经搜索了几个小时,无法弄清楚我做错了什么。这是我在 Java 中的第三个程序,我在作业中迷路了。我必须修改代码以向用户询问颜色,然后一次又一次地询问他们,直到他们猜到“红色”或者他们已经猜不到了。他们尝试了 4 次。我必须给他们反馈“你在 x 次尝试中猜对了”或“你用完了尝试。为了获得满分,我最多需要使用一个循环和一个条件。原始代码使用一段时间来比较颜色并给出无限猜测而不计算。
这是我到目前为止所拥有的,它确实可以编译。但是,如果第一次答案不正确,它会给我带来祝贺和抱歉的信息。如何在不使用另一个循环的情况下解决这个问题?
/*************************************************************************
* Compilation: javac JavaLa2.java
* Execution: java JavaLab3
* Mary Ross
* Date: April 12, 2011
*
* % java JavaLab3
* This program will ask the user for a color. It will ask until they guess “red” OR they have run out of guesses.
* They have four guesses.
* Example:
* What is your name? Jordan
* What color do you guess? White
* let’s try again: What color do you guess? red
* “Congratulations! You guessed the correct color in 2 tries.”
*
* NOTE: I have put a lot of comments to guide you in the code.
*************************************************************************/
import java.io.*;
public class JavaLab3 {
public static void main(String[] args) {
// first we define our input streams.
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
String sName ;
String sColor;
Integer numGuesses = 0;
// we catch exceptions if some are thrown.
try {
System.out.println("what is your name?");
sName = reader.readLine();
// then we will ask for the color
System.out.println("What color do you guess?");
sColor = reader.readLine();
numGuesses = numGuesses +1;
// at this point we have primed the condition for the while loop
while (sColor.compareToIgnoreCase("red") != 0 && numGuesses < 4) {
System.out.println("You have guessed " + numGuesses + " times. You get four guesses.");
System.out.println("Let’s try again: What color do you guess?");
sColor = reader.readLine();
numGuesses = numGuesses + 1;
System.out.println("Sorry, " + sName + " you have exceeded your alloted guesses. The color is red.");
}
System.out.println("Congratulations! " + sName + " You correctly guessed Red in " + numGuesses + " tries.");
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
运行正确答案:
> what is your name?
Mary
What color do you guess?
red
Congratulations! Mary You correctly guessed Red in 1 tries.
运行 1 个错误答案和正确答案:
what is your name?
Mary
What color do you guess?
white
You have guessed 1 times. You get four guesses.
Let’s try again: What color do you guess?
red
Sorry, Mary you have exceeded your alloted guesses. The color is red.
Congratulations! Mary You correctly guessed Red in 2 tries.