gpt4 book ai didi

java - 你猜为什么这段代码会打印无限量的 "What' ?”

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

我正在尝试制作一个范围从 1 到 100 之间的猜数字游戏。如果用户猜对了正确的数字,程序将停止。

我当前的代码:

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

public class GuessingGame {
public static void main(String[] args) {
Random randomNumber = new Random();
Scanner reader = new Scanner(System.in);
System.out.println("What's your guess? ");
int n = reader.nextInt();
reader.close();

int Number = randomNumber.nextInt(100 + 1);
int guess = n;
while (guess != Number) {
System.out.println("What's your guess? ");
new Scanner(System.in);
}

if (guess == Number) {
System.out.println("Your have guessed the correct number! ");
}

else if (guess < Number) {
System.out.println("Your number is too low! ");
}

else if (guess > Number) {
System.out.println("Your number is too high! ");
}
}
}

最佳答案

这就是在 IDE 中使用格式化程序很有帮助的地方。您将能够看到循环之后的 if 条件应该位于循环内部,并且您应该读取来自输入的猜测。

顺便说一句,除非您明确不想再次从中读取任何内容,否则您永远不应该关闭输入。

尝试

 Random randomNumber = new Random();
Scanner reader = new Scanner(System.in);
int number = randomNumber.nextInt(100 + 1);
while(true) {
System.out.println("What's your guess? ");
int guess = reader.nextInt();

if (guess == Number) {
System.out.println("You have guessed the correct number! ");
break; // no need to guess more

} else if (guess < Number) {
System.out.println("Your number is too low! ");

} else if (guess > Number) {
System.out.println("Your number is too high! ");
}
}

关于java - 你猜为什么这段代码会打印无限量的 "What' ?”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51019004/

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