开发者

Why doesn't this for-loop let me input text the first cycle?

What I want to do is ask the user for a number of strings to read into an array, and then ask the user to input that number of strings and read them into the array. When I run this code it never 开发者_如何学Pythonasks me for an input the first cycle of the first for-loop, just prints out "String #0: String #1: " and then I can input text. Why is that and what did I do wrong?

import java.util.Scanner;

public class ovn9 
{
public static void main(String[] args)
{
    Scanner sc=new Scanner(System.in);

    System.out.print("Number of inputs: ");

    int lines= sc.nextInt();
    String[] text=new String[lines];

    for(int x=0; x<text.length; x++)
    {
        System.out.print("String #"+x+": ");
        text[x] = sc.nextLine();
    }

    for(int y=0; y<text.length; y++)
        System.out.println(text[y]);

}
}


Buffering.

nextInt() does not consume the newline in the input buffer that was put there when you entered the number of inputs. In the iteration 0 of the for loop, there's already a line of input in the buffer and nextLine() can complete immediately and the program will wait for new input line only in iteration 1. To ignore the newline in the input, you can add just another nextLine() call before entering the for loop.


Maybe you should change your loop to use 'sc.next()'

for ( int x = 0; x < lines; x++ ) {
    System.out.print("String #" + x + ": ");
    text[x] = sc.next();
}

It can be explained by the Java API

String next(): Finds and returns the next complete token from this scanner.

String nextLine(): Advances this scanner past the current line and returns the input that was skipped.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜