Java 中的第二个数组未显示输出

Output is not showing for second array in Java

我是 Java 编程的初学者,我创建了一个程序,它接受用户输入的 10 个数字并打印它们。第一部分使用 for 循环,第二部分使用 while 循环。第一部分工作正常,第二部分不显示输出。有人能帮帮我吗?

import java.util.Scanner;

public class ArrayOfTenElements {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int numArray1[] = new int [10];
    int numArray2[] = new int [10];
    int i;

    //First Section
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter 10 numbers: ");
    for(i=0;i<10;i++) {
        numArray1[i] = scanner.nextInt();
    }
    System.out.println("The entered numbers are: ");
    for(i=0;i<10;i++) {
        System.out.print(numArray1[i] + " ");
    }
    
    //Second Section
    System.out.println("\nEnter 10 numbers: ");
    int j = 0;
    while(j<10) {
        numArray2[j] = scanner.nextInt();
        j++;
    }
    System.out.println("The entered numbers are: ");
    while(j<10) {
        System.out.print(numArray2[j] + " ");
        j++;
    }
    scanner.close();
}

}

您没有在第一次循环后将变量 j 重置回 0。因此第二个循环以 j 的值 10 开始,因此不会执行 while 循环。

//Second Section
System.out.println("\nEnter 10 numbers: ");
int j = 0;
while(j<10) {
    numArray2[j] = scanner.nextInt();
    j++;
} 
// add this
j = 0;

System.out.println("The entered numbers are: ");
while(j<10) {
    System.out.print(numArray2[j] + " ");
    j++;
}

When you use last for loop j value is 10 in the beginning of that loop as you declare j out of the scope.So you should declare new variable and replace while loop from it.The other thing is you should use for loop to showing array2.Normally we use while loops for only when we not knowing about end time.So we use for loop for this.

//Second Section
System.out.println("\nEnter 10 numbers: ");
int j = 0;
while(j<10) {
    numArray2[j] = scanner.nextInt();
    j++;
}

System.out.println("The entered numbers are: ");
for(i=0;i<10;i++) {
    System.out.print(numArray2[i] + " ");
}