简体   繁体   中英

JAVA- Change 111 to 123

public class Venus1
{
    public static void main(String args[])
    {
        int[]x={1,2,3};
        int[]y={4,5,6};
        new Venus1().go(x);
    }
    void go(int... z)
    {
        for(int i:z)
            System.out.println(z[0]);
    }
}

The output is 111

How do I change the code so it returns 123 ?

Change

System.out.println(z[0]);

to

System.out.println(i);

When you iterate over the array using the enhanced for loop, the variable of the loop ( i in your code) is assigned the current element of the array in each iteration.

What You were doing wrong:

You were trying to print the same index of the array z .

System.out.println(z[0]);

The above statement prints the first index value again and again.

What You need to do:

Since the loop runs over i so you need to print the ith index instead of the same index again and again.

Solution:

Use the following code:

void go(int... z)
{
    for(int i = 0; i < z.length; i ++) {
        System.out.println(z[i]);
    }
}

Hope it's all clear now.

void go(int... z)
{
    for(int i = 0; i < z.length; i ++) {
        System.out.println(z[i]);
    }
}

Your code is almost correct, but you are fetching the first array entry all the time in your loop (z[0] will pick the first entry with index 0 of array z). To change this, loop over the number of entries existing in the array (z.length) and increase variable i each time (start with 0). Use it as your array index inside the loop to get the array entry matching your current iteration.

change

System.out.println(z[0]);

to

 for (int i : z) {
        System.out.println(z[i - 1]);
  }

Change

System.out.println(z[0]);

to

System.out.println(z[i]);

Basically you need to print the ith indices instead of z[0]

Use

System.out.println(z[i]);

instead of:

System.out.println(z[0]);

You should iterate the whole array, not the first index only so you need to print using i instead of 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM