[英]Accepting multiple integers on a single line using Scanner
The user needs to enter a certain number of integers. 用户需要输入一定数量的整数。 Rather them enter an integer at a time, I want to make it so they can enter multiple integers on a single line, then I want those integers to be converted in an array.
宁可让它们一次输入一个整数,我想使它能够在一行上输入多个整数,然后让这些整数在数组中进行转换。 For example, if the user enters:
56 83 12 99
then I want an array to be created that is {56, 83, 12, 99}
例如,如果用户输入:
56 83 12 99
那么我希望创建一个数组,即{56, 83, 12, 99}
In other languages like Python or Ruby I would use a .split(" ")
method to achieve this. 在其他语言(如Python或Ruby)中,我将使用
.split(" ")
方法来实现此目的。 No such thing exist in Java to my knowledge. 据我所知,Java中没有这样的东西。 Any advice on how to accept user input and create an array based on that, all on a single line?
关于如何接受用户输入并基于此创建数组的所有建议都在一行上?
Using the Scanner.nextInt()
method would do the trick: 使用
Scanner.nextInt()
方法可以解决问题:
Input: 输入:
56 83 12 99
56 83 12 99
Code: 码:
import java.util.Scanner;
class Example
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int[] numbers = new int[4];
for(int i = 0; i < 4; ++i) {
numbers[i] = sc.nextInt();
}
}
}
At @user1803551's request on how Scanner.hasNext()
can achieve this: 应@ user1803551要求,如何使用
Scanner.hasNext()
实现此目的:
import java.util.*;
class Example2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (sc.hasNextInt()) { // this loop breaks there is no more int input.
numbers.add(sc.nextInt());
}
}
}
The answer by Makoto does what you want using Scanner#nextLine
and String#split
. Makoto的答案使用
Scanner#nextLine
和String#split
完成了您想要的工作。 The answer by mauris uses Scanner#nextInt
and works if you are willing to change your input requirement such that the last entry is not an integer. mauris的答案使用
Scanner#nextInt
,如果您希望更改输入要求以使最后一个输入项不是整数,则可以使用该方法。 I would like to show how to get Scanner#nextLine
to work with the exact input condition you gave. 我想展示如何使
Scanner#nextLine
与您输入的确切输入条件一起使用。 Albeit not as practical, it does have educational value. 尽管不实用,但确实具有教育价值。
public static void main(String[] args) {
// Preparation
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter numbers:");
// Get the input
while (scanner.hasNextInt())
numbers.add(scanner.nextInt());
// Convert the list to an array and print it
Integer[] input = numbers.toArray(new Integer[0]);
System.out.println(Arrays.toString(input));
}
When giving the input 10 11 12
upon first prompt, the program stores them ( Scanner
has a private
buffer), but then keeps asking for more input. 当在第一次提示时提供输入
10 11 12
时,程序会存储它们( Scanner
具有private
缓冲区),但随后会继续请求更多输入。 This might be confusing since we give 3 integers which loop through hasNext
and expect that when the 4th call is made there will be no integer and the loop will break. 这可能会造成混淆,因为我们给出了3个通过
hasNext
循环的整数,并期望在进行第4次调用时将没有整数,并且循环将中断。
To understand it we need to look at the documentation: 要了解它,我们需要查看文档:
Both
hasNext
andnext
methods [and their primitive-type companion methods] may block waiting for further input.hasNext
和next
方法(及其原始类型的伴随方法)都可能会阻塞等待进一步的输入。 Whether ahasNext
method blocks has no connection to whether or not its associatednext
method will block.hasNext
方法是否阻塞与其关联的next
方法是否将阻塞无关。
(emphasis mine) and hasNextInt
(强调我的)和
hasNextInt
Returns:
true
if and only if this scanner's next token is a valid int value返回值:当且仅当此扫描器的下一个标记是有效的int值时,才返回
true
What happens is that we initialized scanner
with an InputStream
, which is a continuous stream of data. 发生的是,我们使用
InputStream
初始化了scanner
, InputStream
是连续的数据流。 On the 4th call to hasNextInt
, the scanner " does not know " if there is a next int or not because the stream is still open and data is expected to come. 在对
hasNextInt
的第4次调用中,扫描器“ 不知道 ”是否存在下一个int,因为流仍处于打开状态,并且预计将有数据来。 To conclude from the documentation, we can say that hasNextInt
总结一下文档,我们可以说
hasNextInt
Returns
true
if this scanner's next token is a valid int value, returnsfalse
if it is not a valid int, and blocks if it does not know what the next token is.返回
true
当此扫描器的下一个标记是有效的int值,返回false
,如果它不是一个有效的int,并阻止如果它不知道下一个标记是什么。
So what we need to do is close the stream after we got the input: 因此,我们需要做的就是在获得输入后关闭流:
// Get the input
numbers.add(scanner.nextInt());
System.in.close();
while (scanner.hasNextInt())
numbers.add(scanner.nextInt());
This time we ask for the input, get all of it, close the stream to inform scanner
that hasNextInt
does not need to wait for more input, and store it through iteration. 这次我们要求输入,获取所有输入,关闭流以通知
scanner
hasNextInt
不需要等待更多输入,并通过迭代存储它。 The only problem here is that we closed System.in
, but if we don't need more input it's fine. 这里唯一的问题是我们关闭了
System.in
,但是如果我们不需要更多输入,那就很好了。
String#split
exists, but you have to do more work, since you're only getting strings back. String#split
存在,但是您必须做更多的工作,因为您只能收回字符串。
Once you've got the split, convert each element into an int
, and place it into the desired array. 拆分后,将每个元素转换为一个
int
,然后将其放入所需的数组中。
final String intLine = input.nextLine();
final String[] splitIntLine = intLine.split(" ");
final int[] arr = new int[splitIntLine.length];
for(int i = 0; i < splitIntLine.length; i++) {
arr[i] = Integer.parseInt(splitIntLine[i]);
}
System.out.println(Arrays.toString(arr)); // prints contents of your array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.