如何遍历数组中的每个元素?

时间:2019-10-01 11:40:25

标签: java

我正在尝试遍历数组A的每个元素。我无法做到这一点,尽管使用预先固定的数组元素可以奏效。

public class Application {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Number of elements in array B = ");
        int y = scanner.nextInt();

        int B[] = new int[y];

        System.out.println("Enter the elements of array B : ");
        for (int i : B) {
            i = scanner.nextInt();
        }

        System.out.println("Elements of array B : ");
        for (int i : B) {
            System.out.println(i);
        }

    }

}

3 个答案:

答案 0 :(得分:1)

Scanner scanner = new Scanner(System.in);

System.out.print("Number of elements in array B = ");
int y = scanner.nextInt();

int B[] = new int[y];

System.out.println("Enter the elements of array B : ");
for (int i = 0 ; i < y ; i++ ) {
    B[i]= scanner.nextInt();
}

在上面的循环中,不能将每个插入都使用。当您编写for (int i: B)时,它表示B数组中的每个元素i,并且 您的B是空的。因此,请使用传统循环插入,并使用每个循环从数组中获取元素。

System.out.println("Elements of array B : ");
for (int index : B) {
    System.out.println(index);
}

答案 1 :(得分:0)

只需按如下所示编辑您的第一个for循环,它将起作用

for (int i =0; i<y; i++) 
{
    B[i] = scanner.nextInt();
}

答案 2 :(得分:-1)

不确定在输入数组的每个元素时是否为每个循环使用a。 您处在正确的轨道上,因此常规的for循环会更好地为您服务:)