gpt4 book ai didi

java - "if"语句中的局部变量错误 (Java)

转载 作者:行者123 更新时间:2023-12-02 03:24:26 24 4
gpt4 key购买 nike

import java.util.Scanner;
import java.util.Random;
import static java.lang.System.out;

class TestingStuf {
enum tooWhat {tooHigh, tooLow, justRight};

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random myRandom = new Random();

tooWhat guess;

out.println("Pick a number between 1 and 10.");
int userGuess = keyboard.nextInt();
int randomNumber = myRandom.nextInt(10) + 1;

if (userGuess < randomNumber) {
guess = tooWhat.tooLow;
}else if (userGuess > randomNumber) {
guess = tooWhat.tooHigh;
}else if (userGuess == randomNumber) {
guess = tooWhat.justRight;
}

out.println("Your guess is:");

if (guess == tooWhat.tooLow) {
out.println("Too low.");

}else if (guess == tooWhat.tooHigh) {
out.println("Too high.");

}else if (guess == tooWhat.justRight) {
out.println("Correct!");

}

keyboard.close();
}
}

在我的代码中,我在第二组“if”语句中出现错误,指出“局部变量猜测可能尚未初始化”,即使在前面的“if”语句中我给了“guess”变量一个值这取决于用户输入。我做错了什么?

最佳答案

如果你看一下你的代码,似乎有一条通过if...else if...else if的路径,其中猜测 从未被初始化。这就是编译器警告您的内容,因为随后的代码预计 guess 肯定会有一个值。

尽管我们作为人类知道这三个条件是互斥的,但编译器并不像我们那么聪明。只需将最后一个设置为 else 而不是 else if (...):

if (userGuess < randomNumber) {
guess = tooWhat.tooLow;
}else if (userGuess > randomNumber) {
guess = tooWhat.tooHigh;
}else { // *** No `if`
guess = tooWhat.justRight;
}

关于java - "if"语句中的局部变量错误 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39155964/

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