Java 使用 Scanner 在一行上接受多个整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26446147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accepting multiple integers on a single line using Scanner
提问by chopper draw lion4
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. No such thing exist in Java to my knowledge. Any advice on how to accept user input and create an array based on that, all on a single line?
在 Python 或 Ruby 等其他语言中,我会使用一种.split(" ")
方法来实现这一点。据我所知,Java 中不存在这样的东西。关于如何接受用户输入并基于该输入创建数组的任何建议,所有这些都在一行中?
回答by Makoto
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
回答by mauris
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());
}
}
}
回答by user1803551
The answer by Makoto does what you want using Scanner#nextLine
and 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. I would like to show how to get Scanner#nextLine
to work with the exact input condition you gave. Albeit not as practical, it does have educational value.
Makoto 的答案可以使用Scanner#nextLine
和做您想做的事情String#split
。Scanner#nextInt
如果您愿意更改输入要求,使最后一个条目不是整数,那么mauris 的答案就会使用并起作用。我想展示如何Scanner#nextLine
使用您提供的确切输入条件。虽然不那么实用,但它确实具有教育价值。
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. 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.
10 11 12
在第一次提示时给出输入时,程序存储它们(Scanner
有一个private
缓冲区),但随后不断要求更多输入。这可能会令人困惑,因为我们给出了 3 个循环通过的整数,hasNext
并期望在进行第 4 次调用时将没有整数并且循环将中断。
To understand it we need to look at the documentation:
要理解它,我们需要查看文档:
Both
hasNext
andnext
methods [and their primitive-type companion methods] may blockwaiting for further input. Whether ahasNext
method blocks has no connection to whether or not its associatednext
method will block.
既
hasNext
和next
方法[及其基本类型companion方法]可以阻挡等待进一步的输入。一个hasNext
方法是否阻塞与其关联的next
方法是否会阻塞没有关系。
(emphasis mine) and hasNextInt
(强调我的)和 hasNextInt
Returns:
true
if and only if this scanner's next token is a valid int value
返回:
true
当且仅当此扫描器的下一个标记是有效的 int 值
What happens is that we initialized scanner
with an InputStream
, which is a continuousstream of data. 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. To conclude from the documentation, we can say that hasNextInt
发生的事情是我们scanner
用一个初始化InputStream
,它是一个连续的数据流。在第 4 次调用 时hasNextInt
,扫描器“不知道”是否有下一个 int 值,因为流仍处于打开状态并且预计会有数据到来。从文档中得出结论,我们可以说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. The only problem here is that we closed System.in
, but if we don't need more input it's fine.
这一次,我们要求的输入,获得这一切,靠近流,通知scanner
说hasNextInt
并不需要等待更多的投入,并将其存储通过迭代。这里唯一的问题是我们关闭了System.in
,但如果我们不需要更多输入,那就没问题了。