Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

java - 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 asks 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]);

}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...