Java: error: variable was not initialized

I am learning Java and I am getting this error. I know this has been asked several (many) times, but none of the answers seem to answer my question. Code body:

String[] number = {"too small", "one", "two", "three", "four", "too large"};
int i;
if(num<1){
    i=0;
}
if(num==1){
    i=1;
}
if(num==2){
    i=2;
}
if(num==3){
    i=3;
}
if(num==4){
    i=4;
}
if(num>4){
    i=5;
}
return number[i];

where the variable 'num' is declared, initialized, and set earlier. The error I get is: "The variable" I "may not have been initialized" and points to the last line (return number [i];).

The fact is that if I declare "i" and immediately assign a value (int i = 0;), the code works fine. But if I do not assign a value, I get an EVEN error if after each "if" a possible value is assigned.

I do not get such an error with C, for example.

thank

+4
source share
2

Java if, , if i. , if. i .

Java , . 4.12.5 JLS :

:

(§14.4, §14.14) (§14.4) (§15.26)

- i, , .

int i = 0;
// Your if statements are here.
return number[i];
+8

, :

String[] number = {"too small", "one", "two", "three", "four", "too large"};
int i = num;
if (i < 1) { i = 0; }
if (i > 4) { i = 5; }
return number[i];

, num :

String[] number = {"too small", "one", "two", "three", "four", "too large"};
if (num < 1) { num = 0; }
if (num > 4) { num = 5; }
return number[num];

, , , . .

0

Source: https://habr.com/ru/post/1544070/


All Articles