0

I am trying to ask the user for the number of string inputs in a String array and then Display the output as the contents of that String along with Index number. I can only give inputs for size-1 no. of values and the 0 index position is always been kept empty.Why is this happening?

import java.util .*;

public class Main {
    public static void main(String[] args) {
        System.out.println("enter no. of values");
        Scanner sc = new Scanner(System.in);
        int size = sc.nextInt();
        String arr[] = new String[size];
        System.out.println("Enter " + size + " values");
        for (int i = 0; i < size; i++) {
            arr[i] = sc.nextLine();
        }
        System.out.println("The array is");
        for (int i = 0; i < size; i++)
            System.out.println(i + ":" + arr[i]);
    }
}
luk2302
  • 46,204
  • 19
  • 86
  • 119
  • That could be a problem of the next line being empty. Since the user can hit the return key multiple times anyway it might be best to loop until you got all inputs and ignore any empty lines. – Thomas Feb 12 '19 at 13:32
  • `Scanner.nextInt()` and `Scanner.nextLine()` have a **conflict.** If you call `sc.nextInt()` and `sc.nextLine()` afterwards, then `sc.nextLine()` will return an empty String. – FailingCoder Feb 12 '19 at 13:46

1 Answers1

0

Use sc.next()

That will solve your problem

Dinesh Shekhawat
  • 446
  • 6
  • 12