0

I was trying to take input for the number of names to be stored in an array from user and then using that i was taking names from the user ,first i tried to take names from the user using next() method and all the things were fine but when i tried to take input using nextLine() method the output was as shown below

package learningJava;
import java.util.Scanner;

public class practice
{
    public static void main(String[] args)
    {
        int n;
        Scanner obj = new Scanner(System.in);
        System.out.println("Enter the number of names you are gonna enter");
        n = obj.nextInt();

        String names[] = new String[n];
        for(int i=0;i<n;i++)
        {
            System.out.println("Enter the name of friend "+(i+1));
            names[i]=obj.nextLine();
        }
        obj.close();
        System.out.println("Names of your friends are");
        for(int i=0;i<names.length;i++)
        {
            System.out.println(names[i]);
        }
    }
}

Output for the nextLine() method

Enter the number of names you are gonna enter
5
Enter the name of friend 1
Enter the name of friend 2

It is not prompting me to enter the name of friend 1 and directly skipping it and coming to the friend 2 line. I am beginner in Java , i know the basic difference in next and nextLine() that next() doesn't take input after a space but nextLine() takes complete input , So what is happening here ??

LocalHost
  • 823
  • 1
  • 6
  • 17
  • Your issue is answered by this question: https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo. Your call to `nextInt()` doesn't consume the line terminator character (where you pressed Enter at the end of the integer). So when you call `nextLine()` it gets a blank line because it only reads the line terminator. By the way, it's best to name your scanner something more descriptive than `obj`. Also, there's no need to close the Scanner because that closes `System.in` which you may need at a later stage in your program. – Klitos Kyriacou Oct 14 '18 at 12:06

1 Answers1

0

just in for loop, just change "println" to "print" because nextLine() consumes new line character.

import java.util.Scanner;

public class practice
{
    public static void main(String[] args)
    {
        int n;
        Scanner obj = new Scanner(System.in);
        System.out.println("Enter the number of names you are gonna enter");
        n = obj.nextInt();

        String names[] = new String[n];
        for(int i=0;i<n;i++)
        {
            System.out.print("Enter the name of friend "+(i+1));
            names[i]=obj.nextLine();
        }
        obj.close();
        System.out.println("Names of your friends are");
        for(int i=0;i<names.length;i++)
        {
            System.out.println(names[i]);
        }
    }
}

check this answer: Java String Scanner input does not wait for info, moves directly to next statement. How to wait for info?