0

The code is listed below. So I expected the output to be {2 4 6 8 10}, however, when I test it, the result is {1 2 3 4 5}. I am confused now, can anyone tell me why? Thanks!

public class practice{ 
    public void doubler(int[] a)
    {
        int[] b = new int[a.length];
        for(int i = 0; i< a.length; i++)
        {
            b[i] = 2*a[i];
        }
        a = b;
    }
    public static void main(String[] args) 
    {
    int[]c = {1,2,3,4,5};
        Practice w = new Practice();
        w.doubler(c);
        for(int count = 0; count<c.length; count++)
        {
            System.out.print(c[count] + " ");
        }
  }
}

3 Answers3

0

Since double is void method following doesnt work

int[] s=w.doubler(c);

because it would be similar as

int[] s= void; // wrong

change the return type of the method

public int[] doubler(int[] a) 

and return the array b as soon as the method is done with the job

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

I think this is helpful for you,

public class practice{ 
    public int[] doubler(int[] a)
    {
        int[] b = new int[a.length];
        for(int i = 0; i< a.length; i++)
        {
            b[i] = 2*a[i];
        }
        return b;
    }
    public static void main(String[] args) 
    {
    int[]c = {1,2,3,4,5};
        Practice w = new Practice();
        int[] s=w.doubler(c);
        for(int count = 0; count<s.length; count++)
        {
            System.out.print(s[count] + " ");
        }
    } 
}

I your case, you didn't return multiplied array to int[] s.

Kushan
  • 10,657
  • 4
  • 37
  • 41
0

Change method doubler to :

public int[] doubler(int[] a)
    {
        int[] b = new int[a.length];
        for(int i = 0; i< a.length; i++)
        {
            b[i] = 2*a[i];
        }
        return b;
    }

This will give you new array b.

Jay Smith
  • 2,331
  • 3
  • 16
  • 27