Array of numbers with variable quantity Java Android

0

I'm doing a program for Android and I want to make an array of integers, but I need to define the quandity of numbers with a variable that has 3 values: 20, 50 and 100. I tried using the code below:

private int[] listNumbers1 = new int[maxNumber];

    for (int number=0; number<maxNumber; number++) {

    listNumbers1[number] = number+1;

}
    
asked by anonymous 15.12.2017 / 00:09

1 answer

0

Your code will only display problems depending on where you position the listNumbers1 variable.

Basically, you need to position it in the class scope, in case you want to keep the private access modifier, and you can also place it in a method, but you could no longer use the private modifier, since it now belongs to the method.

public class MainScreen extends Activity {

    private int[] listNumbers1; 

    @Override
    public void onCreate(Bundle state) {
        // super....

        int maxNumbers = 50; // Inicialize a variável aqui
        listNumbers1 = new int[maxNumbers]; // crie sua lista utilizando a referência da variável maxNumbers... que já foi inicializada

        for (int number = 0; number < maxNumbers ; number++) {
            listNumbers1[number] = number+1;
        }
    }
}

The code above should work normally. You can also create the listNumbers1 list within the onCreate () method, if you prefer to have it local. But remember that in this case, the keyword private must be removed.

    
15.12.2017 / 01:14