-1

I was working with array and i wanted to make a list that user can set a value for its length and then also user can add some String values duo to it's length that user set up.I wanted the program to show me the list that user entered to user (just practicing) and i found out a different use of next() and nextLine() that nextLine() method wouldn't work properly since i wanted to add as many String as i wanted to my Array.here is what i am thinking:

System.out.println("Welcome to addingCourse wizard :)");
        System.out.println("Please enter the amount of your course: ");
        int z = input.nextInt();
        String[] course = new String[z];

        for (int i = 0; i < course.length ; i++) {

            course[i] = input.nextLine();
        }
        System.out.println("Ok. Here is your list...");

        for (int i = 0; i < course.length; i++) {

            System.out.println(course[i]);
        }

problem is nextLine() wouldn't allow us to add items as we wanted in array.for example if you want your list to be 100, it will allow you to just enter 99 items although next() method allow course.length items and print all items

1 Answers1

0

Take a look at these lines

    int z = input.nextInt();
    String[] course = new String[z];

    for (int i = 0; i < course.length ; i++) {

        course[i] = input.nextLine();
    }

Whenever you hit the enter key, this creates a new line /n character. As soon as you read your integer on the first line, nextInt isnt consuming said char. Take a good look at the output after your lines are being printed, the first line is an empty line.

To consume this new line, add another nextLine() right after you finish reading your int.

int z = input.nextInt();
input.nextLine(); //Consumes the new line character