Java从单行读取多个int [英] Java reading multiple ints from a single line
问题描述
我正在开发一个程序,我希望允许用户在出现提示时输入多个整数。我曾尝试使用扫描仪,但我发现它只存储用户输入的第一个整数。例如:
I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first integer entered by the user. For example:
输入多个整数:1 3 5
Enter multiple integers: 1 3 5
扫描程序只获得第一个整数1。是否有可能从一行获得所有3个不同的整数,并能够在以后使用它们?这些整数是我需要根据用户输入操作的链表中数据的位置。我无法发布我的源代码,但我想知道这是否可行。
The scanner will only get the first integer 1. Is it possible to get all 3 different integers from one line and be able to use them later? These integers are the positions of data in a linked list I need to manipulate based on the users input. I cannot post my source code, but I wanted to know if this is possible.
推荐答案
我一直在hackerearth上使用它
I use it all the time on hackerearth
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
a[i] = Integer.parseInt(strs[i]);
}
这篇关于Java从单行读取多个int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!