-1
import java.util.Scanner;

public class TestOnly {    
    public static void main(String[] args) throws Exception {
        Scanner sc=new Scanner(System.in);
        int iteration=sc.nextInt();
        int i=0;        
        for(i=1;i<=iteration;i++)
        {          
        System.out.println("Hello World!");
        String input=sc.nextLine();
        System.out.println(input);
        }
}
}

If I give input 1 for iteration variable then the for loop runs for one time. At that time I should be able to take a String input.

But String input can be taken from the second loop. Please explain the reason if you know. Thank you.

Batman
  • 9
  • 1
  • Please look at [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). You're leaving a dangling end-of-line token with the `sc.nextInt()` which is being handled by your `sc.nextLine()` call, and this is messing you up. This is a very common error. One solution is to simply call `sc.nextLine();` after `sc.nextInt()`. The duplicate Q&A will explain the details. – Hovercraft Full Of Eels Aug 15 '23 at 23:56

0 Answers0