基本上我想在我的猜谜游戏中输入一个评分系统,我现在已经构建了以下代码。目前,当用户猜出正确的数字时,他们被告知他们的分数当前设置为10.我想要做的是将分数设置为10,并且每次猜测不正确时该值减1。 当用户正在玩游戏时,我也难以实现退出功能。你们可以建议我如何将这些内容添加到我的代码中吗? 注意:我正在服务器上进行猜谜游戏,我将发布协议部分。
协议
import java.util.*;
public class KKProtocol {
int guess = 0, number = new Random().nextInt(100) + 1;
int score = 0;
Scanner scan = new Scanner(System.in);
public String processInput(String theInput) {
String theOutput = null;
System.out.println("Please guess the number between 1 and 100.");
while (guess != number) {
try {
if ((guess = Integer.parseInt(scan.nextLine())) != number) {
System.out.println(guess < number ? "Higher..." : "Lower...");
}
else {
System.out.println("Correct!");
score = 1;
}
}
catch (NumberFormatException e) {
System.out.println("Please enter a valid number! If you want to Quit just say'Goodbye'");
}
}
return theOutput;
}
}
答案 0 :(得分:1)
你可以这样做:
if (score > 0 && (guess = Integer.parseInt(scan.nextLine())) != number) {
System.out.println(guess < number ? "Higher..." : "Lower...");
score--;
}
...
答案 1 :(得分:1)
错误猜测降低分数:
if ((guess = Integer.parseInt(scan.nextLine())) != number) {
System.out.println(guess < number ? "Higher..." : "Lower...");
score = score - 1
}
要结束游戏,您可以执行以下操作:
boolean gameRunning = true;
while (guess != number && gameRunning) {
String input = scan.nextLine();
if (input.toLowerCase().equals("Goodbye")) { // check for goodbye
gameRunning = false;
} else {
try {
if ((guess = Integer.parseInt(input)) != number) {
...
您还可以使用break
语句打破循环。