1

I'm trying to scan an integer and run a loop to scan strings until that integer. But this code skips the first string...

import java.util.ArrayList;
import java.util.Scanner;

public class A1 {

    public static void main(String[] args) {
        ArrayList <String> A = new ArrayList<String>();
        Scanner sc = new Scanner(System.in);
        System.out.println("How many strings to add:");
        int a = sc.nextInt();
        for(int i=0; i<a; i++)
        {
            System.out.printf("Enter %dth string:\n", i+1);
            String s = sc.nextLine();
            A.add(s);
        }

        for(int i=0; i<A.size(); i++)
        {
            System.out.println(A.get(i));
        }
    }

}

Any solution?

p32929
  • 99
  • 1
  • 11
  • 2
    This might help: [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods](http://stackoverflow.com/q/13102045/669576). – Johnny Mopp Nov 16 '16 at 12:23

1 Answers1

0

Just change your code to following:

import java.util.ArrayList;
import java.util.Scanner;

public class A1 {

    public static void main(String[] args) {
        ArrayList <String> A = new ArrayList<String>();
        Scanner sc = new Scanner(System.in);
        System.out.println("How many strings to add:");
        int a = sc.nextInt();
        for(int i=0; i<a; i++)
        {
            System.out.printf("Enter %dth string:\n", i+1);
            String s = sc.next();         //This will wait until you give argument
            A.add(s);
        }

        for(int i=0; i<A.size(); i++)
        {
            System.out.println(A.get(i));
        }
    }

}

Go through the SO post - Java Scanner doesn't wait for user input

Community
  • 1
  • 1
Chirag Parmar
  • 829
  • 11
  • 23