将输入读取为数组
当我输入“read 1 2 3 4”时,我想从输入流读取一些内容并将其存储在 int[] 中。我应该怎么办?
我不知道数组的大小,一切都是动态的......
这是当前的代码:
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
String line = stdin.readLine();
StringTokenizer st = new StringTokenizer(line);
String command = st.nextToken();
if (command.equals("read")) {
while (st.nextToken() != null) {
//my problem is no sure the array size
}
}
I want to make something read from inputstream to store in an int[] when I type "read 1 2 3 4". what should i do?
I do not know the size of the array, everything is dynamic...
Here is the current code:
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in));
String line = stdin.readLine();
StringTokenizer st = new StringTokenizer(line);
String command = st.nextToken();
if (command.equals("read")) {
while (st.nextToken() != null) {
//my problem is no sure the array size
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用带有节点的存储结构,可以轻松地逐个追加,或者,如果您确实必须使用数组,则需要在必要时定期分配空间。
You either use a storing structure with nodes, that you can easily append one after another, or, if you really must use arrays, you need to allocate space periodically, as it becomes necessary.
从字符串中解析出数据和关键字,然后将其推入如下所示:
Parse-out the data and keyword from your string then push it into something like this:
您需要构建一些东西来解析输入流。假设它实际上像您所指出的那样不复杂,您需要做的第一件事就是从
InputStream
中获取该行,您可以这样做:或者您可以使用
BufferedReader< /code> (正如注释所建议的):
一旦你有一行要处理,你需要将它分成几部分,然后将这些部分处理成所需的数组:
我确信其中一些方法可以抛出异常(至少
read
和parseInt
做),我将把处理这些作为练习。You need to build something to parse the input stream. Assuming it's literally as uncomplex as you've indicated the first thing you need to do is get the line out of the
InputStream
, you can do that like this:Or you can use a
BufferedReader
(as suggested by comments):Once you have a line to process you need to split it into pieces, then process the pieces into the desired array:
I'm sure some of these methods can throw exceptions (at least
read
andparseInt
do), I'll leave handling those as an exercise.