这段代码:
import java.util.*;
import java.io.*;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++) arr[i] = sc.nextInt();
for(int i : arr) System.out.println(arr[i]);
}
}
输出:
2
3
4
1
2
使用此输入:
5 1
1 2 3 4 1
另一方面
这段代码:
import java.util.*;
import java.io.*;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int arr[] = new int[n];
for(int i = 0; i < n; i++) arr[i] = sc.nextInt();
for(int i = 0; i < n; i++) System.out.println(arr[i]);
}
}
Outputs:
1
2
3
4
1
在第一个代码片段中,foreach 循环应该打印数组的元素,但我不明白这些数字是什么以及这些数字如何成为该数组的元素。
因为接下来的一行,
for(int i : arr) System.out.println(arr[i]);
你正在打印arr[i]
而不是i
本身
这里arr[i]
根据您的输入尝试访问 1,2,3,4 和 1 处的元素,如下所示
arr[0]-->1
arr[1]-->2
arr[2]-->3
arr[3]-->4
arr[4]-->1
但是,增强型 for 循环给出的值不是每次迭代的索引
将其替换为以下行,您将看到相同的输出
for(int i : arr) System.out.println(i);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)