1

The following program is expected to accept 'T' number of input strings in the String array, and display them. But it accepts and displays one string less then expected. Why is it so? The program is:

import java.util.Scanner;

public class JavaApplication1
{

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int T =  sc.nextInt();
        String s[] = new String[50];
        for (int i = 0; i < T; i++)
        {
        s[i] = sc.nextLine();
        }

        for (int i = 0; i < T; i++)
        {
            System.out.println(s[i]);
        }
    }

}
Sparsh
  • 25
  • 1
  • 4
  • Possible duplicate of [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods](http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – resueman Sep 18 '16 at 13:23
  • This isn't a duplicate of that question. The question asked above involves the use of 'nextInt' along with 'nextLine'. My question consists only of 'nextLine'. – Sparsh Sep 18 '16 at 13:28
  • 1
    It has a `nextInt` when you ask the user for `T`. – resueman Sep 18 '16 at 13:29
  • 1
    By the way: it is simply wrong to ask the user for the number of array elements; to then create an array with 50 entries. Either your array should have always 50 entries (then you dont ask the user); or you create an array of the size the user wants. And: T is a bad name for a variable. – GhostCat Sep 18 '16 at 13:36
  • Oops. I'm sorry. @resueman – Sparsh Sep 18 '16 at 13:37
  • Yeah GhostCat, I'll keep these things in mind. I suck at programming as of now. Will try to get better at it. – Sparsh Sep 18 '16 at 13:39

2 Answers2

1

The reason of this situation is that the line:

int T =  sc.nextInt();

is reading only the int value, and stays in the same line, so the next execution of nextLine() method reads from the same line, which contains integer value.
To avoid this situation you can use:

int T = Integer.parseInt(sc.nextLine());

For more, you can look here.

Community
  • 1
  • 1
Michał Szewczyk
  • 5,656
  • 7
  • 28
  • 41
-1

Try to do this:

public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);
    System.out.println("Number?");
    int x =  sc.nextInt();
    String[] s = new String[x];
    System.out.println("Words?");
    for (int i = 0; i < x; i++)
    {

        s[i] = sc.next();
        //s[i] = sc.nextLine();
    }

    for (int i = 0; i < x; i++)
    {
        System.out.println(s[i]);
    }
    System.out.println("End.");

Replace nextLine by next()... It seem there's a reason to get this event when you use nextLine...? i'm wonder...

YannXplorer
  • 85
  • 1
  • 5