变量可能未初始化错误 [英] Variable might not have been initialized error

查看:43
本文介绍了变量可能未初始化错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试编译它时:

public static Rand searchCount (int[] x)
{
    int a ;
    int b ;

    ...

    for (int l= 0; l<x.length; l++)
    {
        if (x[l] == 0)
        a++ ;
        else if (x[l] == 1)
        b++ ;
    }

    ...

}

我收到这些错误:

Rand.java:72: variable a might not have been initialized
                a++ ;
                ^
Rand.java:74: variable b might not have been initialized
                b++ ;
                ^
2 errors

在我看来,我在方法的顶部初始化了它们.怎么了?

It seems to me that I initialized them at the top of the method. What's going wrong?

推荐答案

声明它们,但你没有初始化它们.初始化它们就是将它们设置为一个值:

You declared them, but you didn't initialize them. Initializing them is setting them equal to a value:

int a;        // This is a declaration
a = 0;        // This is an initialization
int b = 1;    // This is a declaration and initialization

你得到错误是因为你没有初始化变量,但是你在 for 循环中增加了它们(例如,a++).

You get the error because you haven't initialized the variables, but you increment them (e.g., a++) in the for loop.

Java 原语具有默认值,但正如一位用户在下面评论的那样

Java primitives have default values but as one user commented below

当声明为类成员时,它们的默认值为零.局部变量没有默认值

Their default value is zero when declared as class members. Local variables don't have default values

这篇关于变量可能未初始化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆