【问题标题】:Variables are not initialized in if statement [duplicate]if语句中未初始化变量[重复]
【发布时间】:2018-04-28 13:16:37
【问题描述】:

我正在尝试以下代码。

    int index, use, comp;
    for (index = 0; index < 3; index++)
    {
        if (user1.equalsIgnoreCase(options[index]))
        {
            use = index;
        }
    }
    for (index = 0; index < 3; index++)
    {
        if (opt.equalsIgnoreCase(options[index]))
        {
            comp = add + index;
        }
    }
    int sum = comp + use;

int sum = comp + use; 行,我收到一条错误消息,指出变量 comp 和 use 未初始化。如何将执行循环期间获得的值存储在这些变量中?

【问题讨论】:

  • if 不是循环
  • int index = 0, use = 0, comp = 0; 应该让它工作。问题是 if 语句不能保证运行,在这种情况下,use 变量不会有赋值。

标签: java loops variables


【解决方案1】:

编译器告诉您,当您到达int sum = comp + use; 行时,compuse 可能还没有被赋予值。这显然是正确的(从编译器的角度来看):无法确定这些变量中是否有值。

解决这个问题的一个简单方法是在开始时初始化它们:

int comp = 0;
int use = 0;

但首先要确保这不会破坏您想要的功能。

【讨论】:

    【解决方案2】:

    你需要在for循环内计算总和,否则,这两个变量将是可访问的(循环外)。

     int index;
     int sum = 0;
     int comp= 0;
     int use = 0; 
     //would've been better if you specified what these variables are for though.
    
        for (index = 0; index < 3; index++)
        {          
            if (user1.equalsIgnoreCase(options[index]))
            {
                use = index;
            }
            if (opt.equalsIgnoreCase(options[index]))
            {
                comp = add + index;
            }           
            sum = comp + use;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-22
      • 1970-01-01
      相关资源
      最近更新 更多