1

am new to Java programming.and I just want to print the n strings entered by the user where "n" is the number of test cases entered by the user aswell. so here is my code below ...but nextLine() method is not taking input from the user at the base case(i.e at int i=0). the code is

import java.util.Scanner;
import java.io.InputStreamReader;

         public class Stringprint{
         public static void main(String[] args){  
             String str;
             int testcase;
             Scanner scanIn = new Scanner(System.in);
             System.out.println("Enter the number of testcases :");
             testcase = scanIn.nextInt();
           for(int i = 0; i < testcase ; i ++){

                System.out.println("Enter the String" + i + ":");
                str = scanIn.nextLine(); 
                System.out.println(string);
     }
  }

}

out put of above code is getting like :

Enter the number of testcases :
4

Enter the String0:

Enter the String1:

hello

hello

Enter the String2:

hai

hai

Enter the String3:

bye

bye

so where am I getting wrong..why it isn't asking input string at i=0 ? did i do anything wrong here ?

læran91
  • 321
  • 1
  • 9
  • 1
    The problem is due to nextLine(). Instead use next() and it will work fine.. – Ashish Ani Dec 22 '15 at 04:07
  • 2
    Possible duplicate of [Skipping nextLine() after using next(), nextInt() or other nextFoo() methods](http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods) – resueman Dec 22 '15 at 04:07
  • this may clear : http://stackoverflow.com/a/20190113/5188230 – Ashish Ani Dec 22 '15 at 04:11
  • here you can get better understanding http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods – Zia Dec 22 '15 at 04:29
  • Thank you guys... :) your comments helped me a lot :) – læran91 Dec 25 '15 at 03:23

3 Answers3

1

Try using scanIn.nextLine() right after the call to scanIn.nextInt() and before the loop. The line has not ended after the call to nextInt(). So the new line character is returned by the call to nextLine().

Pubudu
  • 905
  • 7
  • 15
0

Scanner.nextInt() is advancing the cursor past 4 but past new line.

When the first call to Scanner.nextLine() executes, the input begins with a new line so it returns an empty line.

dolan
  • 1,339
  • 8
  • 18
0

A simple fix:

Add 'scanIn.nextLine();' after 'testcase = scanIn.nextInt();' to eat the '\n' character which is not consumed by nextInt().

D_S_toowhite
  • 573
  • 3
  • 15