gpt4 book ai didi

java - Java 中的 while 循环同时返回祝贺和抱歉消息

转载 作者:行者123 更新时间:2023-11-30 09:23:49 25 4
gpt4 key购买 nike

<分区>

我已经搜索了几个小时,但无法弄清楚我做错了什么。这是我的第三个 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.

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com