-3

I need to solve a problem when take an input of integer which are the number of lines the user wants to input just next to this input(some sentences) as understandable from text as follows:

The first line of input contains a single integer N, indicating the number of lines in the input. This is followed by N lines of input text.

I wrote the following code:

public static void main(String args[]) {

    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    String lines[] = new String[n];
        for(int i = 0; i < n; i++){
            System.out.println("Enter " + i + "th line");
            lines[i] = scan.nextLine();
        }
    }
}

And an interaction with the program:

5(The user inputted 5)
Enter 0th line(Program outputted this)
Enter 1th line(Doesn't gave time to input and instantly printed this message)
Hello(Gave time to write some input)
Enter 2th line(Program outputted this)
How(User input)
Enter 3th line(Program outputted this)
Are(User input)
Enter 4th line(Program outputted this)
You(User input)
  • What's the problem? I can't input 0th line.
  • Suggest a better method to input n numbers of lines where n is user provided to a string array.
Unihedron
  • 10,902
  • 13
  • 62
  • 72
RE60K
  • 621
  • 1
  • 7
  • 26

2 Answers2

7

The call to nextInt() is leaving the newline for the 0th call to nextLine() to consume.

Another way to do it would be to consistently use nextLine() and parse the number of lines out of the input string.

Start paying attention to style and code formatting. It promotes readability and understanding.

public static void main(String args[]) {
    Scanner scan = new Scanner(System.in);
    int n = Integer.parseInt(scan.nextLine());
    String lines[] = new String[n];
    for (int i = 0; i < n; i++) {
        System.out.println("Enter " + i + "th line");
        lines[i] = scan.nextLine();
    }
}
Unihedron
  • 10,902
  • 13
  • 62
  • 72
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • I don't understand your question. The other lines do consume the contents and the newline. Only the first one did not. Did you try the change? Did it work? – duffymo Oct 14 '14 at 15:01
-1

I don't know what you would consider better: Try changing

System.out.println("Enter " + i + "th line");

to

System.out.print("Enter " + i + "th line:");

Makes it look better.

A better way of inputting lines would be to keep reading input lines until you see a special termination char. Use an ArrayList to store the lines then you don't need to declare the size beforehand

Unihedron
  • 10,902
  • 13
  • 62
  • 72
Robert3452
  • 1,354
  • 2
  • 17
  • 39