Java: How to initialize an int array in case of a switch?

How can I initialize an integer array in Java, for example: int[] array = {1,2,3};inside a switch statement?

Currently I can write:

switch(something) {
    case 0: int[] array = {1,2,3}; break;
    default: int[] array = {3,2,1};
}

But when I try to access a variable array, eclipse will complain that it cannot be initialized.

If I try to declare it as int[] array;or int[] array = new int[3];, and then the switch statement, I would say that I am trying to update it.

How can I solve this problem? The final idea is to be able to initialize an array with 10 values ​​in one line of code based on some logic (switch statement).

+5
source share
4 answers

switch. .

int[] array;
switch (something) {
    case 0: array = new int[] {1, 2, 3}; break;
    default: array = new int[] {3, 2, 1};
}
+14

switch, = { 1, 2, 3} . , array = new int[] {1, 2, 3};

+1
int[] array;
switch (something) {
    case 0: array = new int[]{1, 2, 3}; break;
    default: array = new int[]{3, 2, 1};
}
+1

. , .

. Java . ,

case 1: int arr = whatever and case 2 : int arr = ... , .

2: :

case 1: int arr = whatever and case 2 : arr = ..., , int arr case 1, - , java , each and every local var has to be declared and initialized before its use.

therefore, the best way is to declare it outside of your switch and define or initialize it anyway you prefer.

0
source

All Articles