簡體   English   中英

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++;
}

當您在循環開始時使用 last for 循環 j 值是 10,因為您將 j 聲明為超出范圍。因此,您應該聲明新變量並從中替換 while 循環。另一件事是您應該使用 for 循環來顯示數組 2 .通常我們只在不知道結束時間時才使用 while 循環。所以我們使用 for 循環。

//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] + " ");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM