为什么没有这样的循环让我输入文本的第一个周期? [英] Why doesn't this for-loop let me input text the first cycle?

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

问题描述

我想要做的就是要求用户提供一些字符串读入一个数组,然后要求用户输入的数字字符串,并将其读入阵。当我运行这个code它从来没有要求我输入的第一个for循环的第一个周期,只需打印出字符串#0:字符串1:然后我可以输入文本。这是为什么,什么我做错?

 进口java.util.Scanner中;公共类ovn9
{
公共静态无效的主要(字串[] args)
{
扫描仪SC =新的扫描仪(System.in);System.out.print(输入号码:);INT线= sc.nextInt();
的String [] =文字新的String [线];为(中间体X = 0; X&下; text.length; X ++)
{
System.out.print(字符串#+ X +:);
文[X] = sc.nextLine();
}对于(INT Y = 0; Y< text.length; Y ++)
的System.out.println(文[Y]);}
}


解决方案

缓冲。

nextInt()不消耗输入缓冲区换行符时输入的输入数被放在那里。在迭代0的循环,有已经输入缓冲区中的一行, nextLine()可以立即完成,程序将等待只能在迭代的新输入行1.要忽略输入换行符,可以在进入循环前添加只是一个 nextLine()电话。

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

}
}

解决方案

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.

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

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