How do I print the user's input (Array) in java?

Joshua Lagos :

The output keeps showing 0, how can I change it? I want to print the user's array however my output takes the users input and print 0

public static void main(String[] args) {
    int i;
    int userArray[] = new int [50];

    Scanner lagoScan = new Scanner(System.in);

    System.out.print("Input Column of Array: ");
    int colInput = lagoScan.nextInt();

    for(i=1; i<= colInput; i++) {
        userArray [i] = lagoScan.nextInt();
    }
    System.out.println(userArray[i]);
}
Elliott Frisch :

Your loop currently starts at the second index of the array, and you print the last index past colInput+1 (which you never set) so you get the default value of 0. Also, instead of hardcoding the length of 50 you should use the user provided value to declare the array. Finally, use Arrays.toString(int[]) to print the entire array (and limit variable scope when possible). Like,

int colInput = lagoScan.nextInt(); 
int[] userArray = new int[colInput];
for (int i = 0; i < colInput; i++) {
    userArray[i] = lagoScan.nextInt();
}
System.out.println(Arrays.toString(userArray));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23619&siteId=1