0

Whenever I use sc.nextLine in java I get this error. It skips one line. Anybody knows how to fix it. sc.nextLine fails for multiple test cases as takes skips one line and then take input. Anybody knows another way to take sentence input in java?

For Input:

2
geeksforgeeks
geeks for geeks

your output is:

geeksforgeeks

Code:

class GFG {
    public static void main (String[] args) 
    {
        Scanner sc=new Scanner(System.in);
        int testcases=sc.nextInt();
        while(testcases--!=0)
        {
            String str=sc.nextLine();
            System.out.println(str);
        }
        //code
    }
}
ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83

1 Answers1

0

you have to read a line after int testcases=sc.nextInt(); because reading the Int from scanner is not reading a line Termination chars....

public static void main (String[] args) 
{
    Scanner sc=new Scanner(System.in);
    int testcases=sc.nextInt();
    sc.nextLine();  //<--HERE!
    while(testcases--!=0)
    {
        String str=sc.nextLine();
        System.out.println(str);
    }
ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83