gpt4 book ai didi

java - 如何让用户重新输入一个值直到它有效

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:17:51 26 4
gpt4 key购买 nike

我在网页设计上花了很多时间后最近开始学习 Java,但是当我尝试创建一个简单的猜谜游戏程序时遇到了一个问题。

        final int MAX = 15;
int answer, guess;
Scanner scan = new Scanner (System.in);

Random generator = new Random();
answer = generator.nextInt(MAX) + 1;

System.out.println("I'm thinking of a number between 1 and " + MAX + ". Guess what is it: ");

guess = scan.nextInt();

if (guess > MAX)
System.out.println("Please choose a number between 1 and 15.");
if (guess == answer)
System.out.println("You got it! Good guessing!");
else
{
System.out.println("This isn't correct, sorry!");
System.out.println("The number was " + answer);

我希望这样,如果用户输入的值大于 15,它会将用户发回以重新输入 1 到 15 之间的有效数字。

首先,如果我知道它尚未完成,因为这是我计划添加此功能的地方。

最佳答案

先看看 Control Flow Statements‌​ ,特别是 for-loopwhile-loopdo-while-loop

部分

基本上,您需要某种循环,它将继续重复直到满足某些退出条件(即在您指定范围内的值)

有点像...

do {

System.out.print("Please choose a number between 1 and " + max + ":");
guess = scan.nextInt();

} while (guess < 1 || guess > 15);

这基本上会继续提示用户,直到他们输入一个介于 1 和 15 之间的值。

作为一个可运行的例子...

import java.util.Random;
import java.util.Scanner;

public class GuessMe {

public static void main(String[] args) {

int max = 15;

int guess = 0;
Random generator = new Random();
int answer = generator.nextInt(max) + 1;
Scanner scan = new Scanner(System.in);

System.out.println("I'm thinking of a number between 1 and " + max + ". Guess what is it\n");
do {

do {

System.out.print("Please choose a number between 1 and " + max + ":");
guess = scan.nextInt();

} while (guess < 1 || guess > 15);

if (guess < answer) {
System.out.println("Good guess, but mine is higher");
} else if (guess > answer) {
System.out.println("Good guess, but mine is low");
}

} while (guess != answer);

System.out.println("Good guess, that's right!");

}

}

已更新

严格来说,您不需要内部循环(在本例中),但它确实展示了您如何能够重新提示用户输入单个给定值。

另一种方法可能是使用 if-else block ,而不是更直接地检查输入的结果。

import java.util.Random;
import java.util.Scanner;

public class GuessMe {

public static void main(String[] args) {

int max = 15;

int guess = 0;
Random generator = new Random();
int answer = generator.nextInt(max) + 1;
Scanner scan = new Scanner(System.in);

System.out.println("I'm thinking of a number between 1 and " + max + ". Guess what is it\n");
do {

System.out.print("Please choose a number between 1 and " + max + ":");
guess = scan.nextInt();

if (guess < 1 || guess > 15) {
System.out.println("You did't enter a valid number, please try again");
} else if (guess < answer) {
System.out.println("Good guess, but mine is higher");
} else if (guess > answer) {
System.out.println("Good guess, but mine is low");
}

} while (guess != answer);

System.out.println("Good guess, that's right!");

}

}

关于java - 如何让用户重新输入一个值直到它有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32642212/

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