Search code examples
javaarraysstringjava.util.scanner

User input stored in a String array


I'm trying to get the user's input stored in an array. Can you help me understand what I am doing wrong in initializing the for loop?

import java.util.Scanner;

public class NameSorting {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String[] array = new String[20];
        System.out.println("Please enter 20 names to sort");              
        Scanner s1 = new Scanner(System.in);
        for (int i = 0; i < 0;) {
            array[i] = s1.nextLine();
        }

        //Just to test
        System.out.println(array[0]);
    }
}

Solution

  • Since you know that you want to have an array of 20 string:

    String[] array = new String[20];
    

    Then your for loop should use the length of the array to determine when the loop should stop. Also you loop is missing an incrementer.

    Try the following code to get you going:

    public static void main(String[] args) throws Exception {
        Scanner s = new Scanner(System.in);
        String[] array = new String[20];
    
        System.out.println("Please enter 20 names to sort");
    
        for (int i = 0; i < array.length; i++) {
            array[i] = s.nextLine();
        }
    
        //Just to test
        System.out.println(array[0]);
    }