【问题标题】:Java, Access variable outside IF-statement [duplicate]Java,IF语句之外的访问变量[重复]
【发布时间】:2018-04-15 10:11:37
【问题描述】:

我无法编译这个程序。有没有人看到我做错了什么?在 if 语句之后,变量 matchOdds 似乎不存在。但我想打印出来。

    /*
    Simple program to print out the game-odds of the result the user chooses in a match; either home, draw or away.
     */

    //Asks the user what he thinks the result is:
    String match = showInputDialog("Choose home(H), draw(D) or away(A):");

    //Converts the answer from string to char:
    char matchRead = match.charAt(0);

    //Depending on what the user thinks the result is, the match-odds is taken from one of the three if-statements:
    double matchOdds;
    if (matchRead == 'H') {
        matchOdds = 1.20;
    } else if (matchRead == 'D') {
        matchOdds = 2.30;
    } else if (matchRead == 'A') {
        matchOdds = 3.45;
    }

    //And then I wanted it to print the odds, i.e. 2.30 if the user chose 'D' ...But it dosent compile because "Variable matchOdds might not have been initialized":
        System.out.println(matchOdds);

【问题讨论】:

  • 它应该要求你初始化它!double matchOdds = 0;

标签: java variables if-statement


【解决方案1】:

您需要在读取之前将matchOdds 初始化为某个双精度值。

double matchOdds = 0.0

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    相关资源
    最近更新 更多