[英]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
输出为111
How do I change the code so it returns 123
? 如何更改代码,使其返回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. 当使用增强的for循环遍历数组时,循环的变量(代码中的i
)将在每次迭代中分配给数组的当前元素。
What You were doing wrong: 您做错了什么:
You were trying to print the same index of the array z
. 您试图打印数组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. 由于循环在i
运行,因此您需要一次又一次打印ith
索引而不是相同的索引。
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). 您的代码几乎是正确的,但是您一直在循环中获取第一个数组条目(z [0]将选择数组z的索引为0的第一个条目)。 To change this, loop over the number of entries existing in the array (z.length) and increase variable i each time (start with 0). 要更改此设置,请遍历数组中存在的条目数(z.length),并每次增加变量i(从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]
基本上,您需要打印第ith
索引而不是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
您应该迭代整个数组,而不仅是第一个索引,因此您需要使用i
而不是0
进行打印
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.