为什么这个 for 循环不让我在第一个循环中输入文本? [英] Why doesn't this for-loop let me input text the first cycle?

查看:25
本文介绍了为什么这个 for 循环不让我在第一个循环中输入文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是要求用户输入多个字符串以读入数组,然后要求用户输入该数量的字符串并将它们读入数组.当我运行这段代码时,它从不要求我在第一个 for 循环的第一个循环中输入,只打印出String #0: String #1:"然后我就可以输入文本了.为什么会这样,我做错了什么?

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

}
}

推荐答案

缓冲.

nextInt() 不会消耗输入缓冲区中的换行符,该换行符在您输入输入数时放置在那里.在 for 循环的第 0 次迭代中,缓冲区中已经有一行输入,nextLine() 可以立即完成,程序将仅在迭代 1 中等待新的输入行.忽略换行符在输入中,您可以在进入 for 循环之前添加另一个 nextLine() 调用.

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.

这篇关于为什么这个 for 循环不让我在第一个循环中输入文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆