【问题标题】:Choosing which input to store where into an ArrayList? (Read from Scanner)选择将哪个输入存储到 ArrayList 中? (从扫描仪读取)
【发布时间】:2015-12-04 06:26:06
【问题描述】:

我正在尝试使用用户输入从扫描仪读取整数列表,并将所有输入存储到 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] + " ");
    }


}

【问题讨论】:

  • 在此处发布您的代码。也就是说,在你的问题中。而不是在外部页面上。
  • 要添加到@Sufian 的评论,欢迎Stack Overflow。要在 编辑 时缩进代码,请将其粘贴到 html 文本框中,突出显示它并按 ctrl-k。
  • 啊,谢谢。所以我猜你可以将粘贴代码复制到文本字段中,它可以告诉它是代码,而不仅仅是常规书写?
  • @LogwanaMan 不,ctrl-k 会将其缩进到适当的级别(4 个空格)被视为代码。

标签: java arraylist java.util.scanner


【解决方案1】:

您可以使用List&lt;Integer&gt;。将所有ints 读入其中,然后(当没有更多ints 时),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.

【讨论】:

  • 谢谢你,我想我只是忘了你可以在列表等上调用一堆有用的方法。
【解决方案2】:

您可以保存列表中的所有数字,而不是将最后一个元素分配给某个变量,然后从列表中删除最后一个元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2014-05-11
    • 1970-01-01
    相关资源
    最近更新 更多