gpt4 book ai didi

java - 猜谜游戏又玩麻烦了

转载 作者:行者123 更新时间:2023-12-01 12:29:58 24 4
gpt4 key购买 nike

好吧,我尝试了一种方法,但每次我出于某种原因输入数字时,它都会显示“您想再玩一次吗”。这是我到目前为止所拥有的。我还能做什么,以便只有在用户猜出正确答案后,它才会询问他/她是否想再次玩?

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

public class GuessNumber {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

Random rand = new Random();
int number = rand.nextInt(100) + 1;
int guess;

System.out.println("Guess the number between 1 and 100\n");

guess = scan.nextInt();

while (true) {
if(guess < number)
System.out.println("Higher!");
else if(guess > number)
System.out.println("Lower!");
else if (guess == number){
System.out.println("Correct!");
}
guess = scan.nextInt();
}
}
}

最佳答案

试试这个

class GuessNumber {

static Random rand = new Random();
static Scanner scan = new Scanner(System.in);
static int number;

public static void main(String[] args) {
playGame();
}

public static void playGame() {
number = rand.nextInt(100) + 1;
System.out.println("Guess the number between 1 and 100");
while (true) {
int guess = scan.nextInt();
if (guess < number) {
System.out.println("Higher!");
} else if (guess > number) {
System.out.println("Lower!");
} else if (guess == number) {
System.out.println("Correct!");
System.out.println("Do you like to play again?[1 for Yes/0 for No]");
int val = scan2.next();
if (val == 1)
playGame();
else
break;
}
}
}
}

或者不使用相同的扫描仪,您可以使用另一个扫描仪并获取字符串输入,如下所示

 else if (guess == number) {
System.out.println("Correct!");
Scanner scan2 = new Scanner(System.in);
System.out.println("Do you like to play again?[Y/N]");
String val = scan2.next();
if (val.equalsIgnoreCase("Y"))
playGame();
else
break;
}

关于java - 猜谜游戏又玩麻烦了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26008307/

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