Variable might not have been initialized error

前端 未结 11 1573
孤城傲影
孤城傲影 2020-11-21 05:50

When i try to compile this:

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

    ...   

    for (int l= 0; l

        
相关标签:
11条回答
  • 2020-11-21 05:57

    You haven't initialised a and b, only declared them. There is a subtle difference.

    int a = 0;
    int b = 0;
    

    At least this is for C++, I presume Java is the same concept.

    0 讨论(0)
  • 2020-11-21 05:57

    Set variable "a" to some value like this,

    a=0;
    

    Declaring and initialzing are both different.

    Good Luck

    0 讨论(0)
  • 2020-11-21 06:02

    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
    

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

    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

    0 讨论(0)
  • 2020-11-21 06:05

    You declared them at the start of the method, but you never initialized them. Initializing would be setting them equal to a value, such as:

    int a = 0;
    int b = 0;
    
    0 讨论(0)
  • 2020-11-21 06:07

    Local variables do not get default values. Their initial values are undefined with out assigning values by some means. Before you can use local variables they must be initialized.

    There is a big difference when you declare a variable at class level (as a member ie. as a field) and at method level.

    If you declare a field at class level they get default values according to their type. If you declare a variable at method level or as a block (means anycode inside {}) do not get any values and remain undefined until somehow they get some starting values ie some values assigned to them.

    0 讨论(0)
  • 2020-11-21 06:08

    You declared them but did not provide them with an intial value - thus, they're unintialized. Try something like:

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

    and the warnings should go away.

    0 讨论(0)
提交回复
热议问题