Array of numbers with variable amount Java Android

Asked

Viewed 117 times

0

I am making 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 options of values: 20, 50 and 100. I tried to use the code below:

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

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

    listNumbers1[number] = number+1;

}

1 answer

0


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

Basically, you need to position it in the class scope if you want to keep the access modifier private, and can also put it into a method, but could no longer use the modifier private, since she 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 above code should work normally. You can also create the list listNumbers1 within the method onCreate(), if you prefer it to be local. But remember that in this case, the keyword private must be removed.

  • I will check if it solves, the strange thing is that this giving an error in this part of the code "number < maxNumber; number++" says that maxNumber and number++ are empty classes, but they are variable!

  • I believe it was because I put it as maxNumber instead of maxNumbers... I was wrong to enter the code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.