[英]is it possible to scan multiple lines of input, each line a new element in an array, when you copy/paste?
Trying to populate an array with input through the scanner .nextLine() function. 尝试使用扫描仪.nextLine()函数的输入填充数组。 The problem specifications give a sample input as follows:
问题规范提供了以下示例输入:
3 5 4
abc
bca
dac
dbc
cba
(ab)(bc)(ca)
abc
(abc)(abc)(abc)
(zyx)bc
Just as I copied and pasted that whole chunk into this box, I'd like to do the same with my code, but when I try, the code only reads in the last line. 就像我将整个块复制并粘贴到此框中一样,我也想对我的代码做同样的事情,但是当我尝试时,代码只会在最后一行读取。 I want each line to be read in and stored in it's own index in the array, NOT a multi-line string in one index or only the last line being read in and stored (which is what is happening now).
我希望每一行都被读入并存储在数组中自己的索引中,而不是一个索引中的多行字符串,或者只读入并存储最后一行(这就是现在发生的情况)。
This is my method for initializing the array, which I've tested and it works when I feed in the input line by line, but that's just really annoying to be honest. 这是我初始化数组的方法,该方法已经过测试,当我逐行输入输入时可以使用,但是说实话,这真令人讨厌。
public static void initialize_array(String [] arr)
{
Scanner kbreader = new Scanner(System.in);
for (int i = 0 ; i < arr.length ; i++)
{
arr[i] = kbreader.nextLine();
System.out.println("this is just loading in: " + arr[i]);
}
}
When I run the program, (it also takes in 3 integers at the top and I print them just to test them, but that's not important) it only registers the last line. 当我运行该程序时(它在顶部也接受3个整数,我只是打印它们以测试它们,但这并不重要),它仅注册最后一行。
A screenshot: enter image description here 屏幕截图: 在此处输入图片描述
I think I've done something like this in C, but that might be because I used scanf() and C is relatively low level so it literally had to walk through the entire chunk. 我想我已经在C语言中做了类似的事情,但这可能是因为我使用了scanf()并且C语言的级别相对较低,因此它实际上必须遍历整个块。
It might not be possible, but I figured I'd ask to see. 可能不可能,但是我想问一下。
Also, just so you know this is for practice, not an actual graded assignment or anything important, so don't hold anything back. 另外,您只知道这是供练习使用的,而不是实际的分级作业或任何重要的事情,因此请不要退缩。 :)
:)
If you know the exact length of the array, then this would work: 如果您知道数组的确切长度,则可以使用:
Scanner scn = new Scanner(System.in);
scn.useDeliminator("\n");
for (int i = 0 ; i < arr.length ; i++)
{
arr[i] = scn.next();
System.out.println("this is just loading in: " + arr[i]);
}
The key here is the useDeliminator
method call. 这里的关键是
useDeliminator
方法调用。 The next
methods reads from the stream until it reaches the deliminator pattern. next
方法从流中读取数据,直到其到达分隔符模式为止。 In this case, it is \\n
, a new line. 在这种情况下,它是
\\n
,换行。 Please use the new line character of your OS. 请使用操作系统的换行符。
这可能array.add(scanner.next())
,但是您是否尝试过仅使用array.add(scanner.next())
并循环运行,直到scanner.hasNext()
返回false?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.