这是我制作的猜谜游戏的代码。我的计数器没有增加到1以上。我正在从单独的控制器类传递参数choice和generateNumber。 do while循环是否应该在控制器类中?
public String startGuessingGame(int choice, int generatedNumber) {
int count = 0;
final int attempts = 4;
String result = null;
do {
count++;
if (choice == generatedNumber) {
result = "Attempt " + count + " "
+ "- You have guessed the correct number!";
}
else if (choice > 50 || choice < 0) {
result = "Out of range. "
+ "\nPlease choose a number between 1 and 50.";
}
else if (choice > generatedNumber) {
result = "Attempt " + count + " "
+ " - You have guessed too high!";
}
else if (choice < generatedNumber) {
result = "Attempt " + count + " "
+ "- You have guessed too low!";
}
if (count == attempts) {
result = "You are out of guesses! The number was " + generatedNumber;
}
}
while(count < attempts);
return result;
}
}
答案 0 :(得分:0)
这里没有循环。
您正在寻找类似InternalsVisibleTo
之类的东西。
答案 1 :(得分:0)
您需要将count
设置为控制器类的类变量(成员),并在该类中执行do / while循环,以便startGuessingGame
仅处理用户选择的验证。像这样的东西,但是代码还远远不够完整
public class SomeControllerClass() {
final int attempts = 4;
int count = 0;
public void someMethod() {
int choice = 0;
do {
choice = getChoice();
count++;
String text = otherClass.startGuessingGame(choice, generatedNumber);
while (count < attempts);
}
并且该方法仅进行验证
public String startGuessingGame(int choice, int generatedNumber) {
String result = null;
if (choice == generatedNumber) {
result = "Attempt " + count + " "
+ "- You have guessed the correct number!";
} else if (choice > 50 || choice < 0) {
//and so on
return result;
}
答案 2 :(得分:0)
尝试一下:
在while
条件之前的最后增加计数器:
do{
...
if (count == attempts) {
result = "You are out of guesses! The number was " + generatedNumber;
}
count++;
}while(count < attempts);
return result;
...