gpt4 book ai didi

Java猜谜游戏。如何输入数据验证(范围检查)以及如何输入猜测?

转载 作者:行者123 更新时间:2023-12-02 00:05:22 25 4
gpt4 key购买 nike

我正在为类做一个项目。这是一个猜谜游戏,获得一个随机数,然后用户猜测它是什么。我已经有了该项目的工作版本,但根据我的指示,它需要数据验证(范围检查最好),并且还需要根据用户正确猜测的尝试次数显示特定消息。如果它小于 3,它应该说“干得好!”如果大于 3 但小于 7,则应显示“需要更多练习”之类的内容。如果超过 7,它应该说“需要更多练习”。我不想解构我的整个项目,我只想添加其中,并进行相应的调整。有人可以给我一种编码这些东西的方法吗?

这是我的代码:


import java.util.Scanner;

public class GuessingGameCalc {

private static void displayWelcomeMessage(int max) {
System.out.println("Welome to the Java Guessing Game!");
System.out.println(" ");
System.out.println("I'm thinking of a number between 1 and" + " " + max);
System.out.println(" ");
}

public static int calculateRandomValue(int max){
double value = (int) (Math.random() * max + 1);
int number = (int) value;
number++;
return number;
}

public static void main(String[] args){
final int max = 100;
String prompt = "y";
displayWelcomeMessage(max);
int unit = calculateRandomValue(max);
Scanner sc = new Scanner(System.in);
int counter = 1;

while (prompt.equalsIgnoreCase("y")) {
while (true) {
System.out.println("Please enter a number.");
int userEntry = sc.nextInt();

if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}

if (userEntry < unit) {
System.out.println("Too low! Guess higher!");
}else if (userEntry > unit) {
System.out.println("Too high! Guess lower!");
} else {
System.out.println("Congratulations! You guessed it in" + " " + counter + " " + "tries!\n");
break;
}
counter++;
}

System.out.println("Would you like to try again? Yes or No?");

prompt = sc.next();
System.out.println("Goodbye!");
}
}

public static void validateTheData() { }
}

最佳答案

似乎您需要做的就是传递计数器变量来验证 Data 方法并输出消息,如下所示:

...
while (true) {
System.out.println("Please enter a number.");

int userEntry = sc.nextInt();

if (userEntry < 1 || userEntry > max) {
System.out.println("Invalid guess! Guess again!");
continue;
}

if (userEntry < unit) {
if( (unit - userEntry) > 10 ){
System.out.println("Way Too low! Guess higher!");
} else {
System.out.println("Too low! Guess higher!");
}
} else if (userEntry > unit) {
if( (userEntry - unit) > 10 ){
System.out.println("Way Too high! Guess lower!");
} else {
System.out.println("Too high! Guess lower!");
}
} else {
validateTheData(counter);
break;
}
counter++;
}
...
public static void validateTheData(int count) {
if( count < 3){
System.out.println("Good job!");
} else if( count < 7 ){
System.out.println("Need more practice.");
} else{
System.out.println("Need way more practice.");
}
}

关于Java猜谜游戏。如何输入数据验证(范围检查)以及如何输入猜测?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58160082/

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