简体   繁体   中英

How do I initialize a variable given by an “if then” statement?

I'm trying to make a simple code to play Rock, Paper, Scizzors, there is more to the code however this is the important part

    int comResult = (int)(Math.random() * 3);
    String comChoice;
    if (comResult == 0) {
        comChoice = "rock";
    } else if (comResult == 1) {
        comChoice = "scizzors";
    } else if (comResult == 2) {
        comChoice = "paper";
    }

    String results;
    if (comChoice == humanChoice)

When I get to comparing the computers choice to the humans the computer says that I haven't declared a value for comChoice even though I put it in the if then statement, how do I properly declare the value

You can add an "else" at the end of your condition block to make sure comChoice gets initialized.

if (comResult == 0) {
    comChoice = "rock";
} else if (comResult == 1) {
    comChoice = "scizzors";
} else if (comResult == 2) {
    comChoice = "paper";
} else {
    comChoice = "invalid input";
}

您可以在默认情况下使用switch。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM