Java - 如何从用户获取不确定数量的输入
Java 问题:
我想从用户处获取不确定行数的输入。例如,我希望用户继续以字符串形式输入人名,直到用户没有其他名字可输入为止。我想要一种用户友好的方式来轻松指示用户没有更多输入。该循环可能如下所示。有什么好主意吗?任何有关改进代码片段的提示也将受到赞赏。
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
while( <user still has more input> ) {
System.out.println("Enter name: ");
String s = read.readLine();
...
<do something with s>;
...
}
谢谢你!
Java Question:
I want to take an undetermined number of lines of input from a user. For instance, I want the user to continue entering names of people as strings until the user has no other names to enter. I want a user-friendly way to easily indicate that the user has no more input. The loop may look like the following. Any good ideas? Any tips on improving the snippet of code is appreciated as well.
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
while( <user still has more input> ) {
System.out.println("Enter name: ");
String s = read.readLine();
...
<do something with s>;
...
}
thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要一个不是名称但指示不再有数据的值。空行就好了。您还想查询他们是否真的想退出,这样万一他们不小心按回车键,他们也不会丢失所有数据。
You need a value that isn't a name but indicates no more data. An empty line would be good. You also want to query if they really want to quit, so in case they accidentally hit return they haven't lost all their data.
您可以有一个布尔变量,例如
finished
,并检查用户是否输入'Q'
或其他项目来指示他们已完成。如果是这样,请将finished
设置为true
,您将在下一次迭代时退出循环。这是一个简单的示例,
我还对您的代码进行了一些修改,
s
重命名为更有意义的名称,因为您正在存储用户的name,因此将其更改为name
似乎是合理的。name
变量分配给null
。并非完全必要,但我认为这是一个很好的做法。name
指定了默认值,因此我已将其移到循环之外。You could have a boolean variable, such as
finished
, and check if the user enters'Q'
or another item to indicate that they are finished. If so, setfinished
totrue
and you will exit your loop on the next iteration.Here is a quick example,
I have also modified your code a bit,
s
to something more meaningful, because you are storing the user's name it seemed reasonable to change it toname
.name
variable tonull
. Not totally necessary, but I consider it good practice.name
a default value, I have moved it outside of your loop.一个简单的方法是让用户在完成后输入一个空行。您只需检查是否
line.equals("")
或者之前修剪它。A simple way is to have users enter an empty line when they are done. You'd just check if
line.equals("")
or maybe trim it before.