How to create an array through another?

Asked

Viewed 300 times

2

I have a problem that deals with providing an array to the program and this should return only the odd numbers of this array, and for this I create a new array that receives the values:

public void maiorValorImpar(int[] a) {
    int b= a.length-1;
    int[] arr2= {};
    int i=0;
    while(i<b) {
        if(a[i]%2 != 0) {
            arr2[i]= a[i];
            System.out.println(arr2);
        }
        i++;
    }
} 

However with my current code, I get the following error:

Exception in thread "main" java.lang.Arrayindexoutofboundsexception: Index 0 out of Bounds for length 0

  • 2

    Not directly related, but make a habit of giving names that really indicate what each thing does. maiorValorImpar, for example, it might confuse someone else (or even yourself), since the code is not checking the highest odd value, but copying all the odd ones to another array (something like copiarImpares would be better, for example). The same goes for variables: impares would be much better than arr2, numeros it would be better if a, etc. It may seem a silly detail, but significant names can help even in reasoning when you are assembling logic...

  • 1

    truth, thank you very much, I’ll take your advice into consideration! :)

2 answers

2


This error is due to the attempt to access the first element (Index 0) of arr2, whereas arr2 has no element (length 0) because you declared her with int[] arr2= {}, without any element between the keys.

In the loop you are declaring b as a.length-1, which makes the loop never check the last element of a, because he’s on the index a-length-1, and the condition is i < b, for example:

a.length: 5;
b: a.length-1 = 4;
while (i < b); // o while só passará pelas posições 0, 1, 2 e 3, pois são menores que b (4)

Another thing I noticed was that you assign arr2[i] = a[i], leaving empty spaces if there are even numbers before an odd, because arr2 will be assigned in the position i, for example:

// Usando o seu código, porém assumindo que arr2 possui um tamanho suficiente
a:    [0, 4, 2, 87, 6, 9, 3]
arr2: [ ,  ,  , 87,  , 9, 3]

To correct this, use a variable that stores the current index of arr2:

public static void maiorValorImpar(int[] a) {
    int b = a.length; // Correção da não verificação do último elemento
    int[] arr2 = new int[b];
    int i = 0, j = 0; // j guarda onde será colocado o próximo número em arr2
    while(i < b) {
        if(a[i]%2 != 0) {
            arr2[j]= a[i];
            System.out.println(arr2[j]);
            j++;
        }
        i++;
    }
}

When working with arrays you don’t initially know the size, I recommend using Arraylist (documentation) (w3schools), so you don’t need to allocate spaces in the array that you might not use, like on line 3 of my example (int[] arr2 = new int[b];).

  • Thank you so much! I have just one question, when you define the int[] arr2 = new int [b], why do you use the b variabiel and does not give error?

  • 1

    You’re welcome! When you declare a vector of your size, it expects the size to be an integer number, for example int[] ex = new int[4]. 4 is that whole. b is also an integer, which in this case has the value of a.length, so it is accepted. Being able to declare arrays like this is useful for when you want the array to have a size based on the output of another part of the code.

  • 1

    Another way of thinking would be int variavel = 4, int[] ex = new int[variavel]: "I want the size of the array ex either 4" or "I want the array size ex be it the value contained in variable"

  • Okay. You’ve given me a great help, thank you very much :)

1

Java arrays cannot grow dynamically after you set their length that can no longer be changed. When you do int[] arr2= {}; you are telling the compiler to create the array arr2 with length 0.

To solve you can use a list List<int> and the method ArrayList.toArray( T[] a ) to get the array.

public static void main (String[] args) throws java.lang.Exception
{
    int[] a = { 1, 3, 5 };
    int b = a.length;
    // cria uma lista de int
    List<Integer> arr2 = new ArrayList<Integer>();
    int i = 0; 
    while (i < b) {
        if (a[i] % 2 != 0) {
            // Adiciona a[i] a lista arr2
            arr2.add(a[i]);
            // Imprime o item i da lsta arr2
            System.out.println( arr2.get(arr2.size() - 1) ); // Leia os comentários               
        }
        i++;
    }
    System.out.println(arr2);
}
  • 1

    In Java you can’t do List<int>, has to be List<Integer>. But this creates another problem, because if you try to convert List<Integer> for int[] using toArray the code does not compile, and the solution it’s not that direct. Something else, in doing b = a.length - 1 you are ignoring the last element of the array a, see. And the line printing the item can give error tb, see

  • @hkotsubo: Error here 'int b = a.length - 1;' has to be int b = a.length; or else keep 'int b = a.length - 1;' and dowhile (i <= b).

  • Done editing. Gross failure to mine in underestimating the problem and making head-on.

  • 1

    You may still have a problem with the line that prints the item (inside the if): https://ideone.com/7i4xBM - you should print a[i], nay arr2.get(i), since arr2 will not necessarily have the same size as a, then their indexes won’t be synchronized...

  • You need a parallel counter.

  • 1

    Or uses arr2.get(arr2.size() - 1). Or just print a[i] even.

  • @hkotsubo Print yourself a[i] loses focus of question.

  • Now arr2.get(arr2.size() - 1) is the best solution.

  • 1

    Print a[i] within the if, I see no problem, since it is the element that has just been added in arr2

Show 4 more comments

Browser other questions tagged

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