我正在尝试使用用户输入从扫描仪读取整数列表,并将所有输入存储到 ArrayList 中,除了用户输入的最后一个整数,我想将其存储在整数中,(整数键;)我该怎么做?
我尝试先将其放入 int[] 中,但我不知道用户将输入多少个整数。有没有一种方法可以直接将所有整数读入 ArrayList(不包括最后一个整数),这些整数将存储在 Integer 键中?
到目前为止我所拥有的:
private ArrayList<Integer> theList;
private Integer theKey;
public static void main(String args[])
{
int[] integers = null;
System.out.println("Enter a list of integers, the final being a key");
Scanner scanner = new Scanner(System.in);
int i = 0;
try
{
while (scanner.hasNext())
{
integers[i] = scanner.nextInt();
i++;
}
}
catch (NullPointerException ex)
{
}
for (int k = 0; i < integers.length; i++)
{
System.out.print(integers[k] + " ");
}
}
最佳答案
您可以使用List<Integer>
。阅读全部int
进入其中,然后(当不再有 int
时), remove
最后一个。比如,
System.out.println("Enter a list of integers, the final being a key");
Scanner scanner = new Scanner(System.in);
List<Integer> al = new ArrayList<>();
while (scanner.hasNextInt()) {
al.add(scanner.nextInt());
}
int key = al.remove(al.size() - 1); // <-- the last one is removed, and returned.
关于java - 选择将哪个输入存储到 ArrayList 的何处? (从扫描仪读取),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34082181/