Skip to content
Advertisement

Output is not showing for second array in Java

I’m a beginner in Java programming and I created a program that accepts 10 numbers as input from users and prints them. The first section is using for loop and the second section is using while loop. The first section works properly and the second section isn’t displaying output. Could anybody help me?

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();
}

}

Advertisement

Answer

You are not resetting variable j back to 0 after the 1st loop. so the 2nd loop starts with a value of 10 for j, and hence, while loop is not executed.

//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++;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement