首页 > 解决方案 > 为什么我的数组列表没有保留最后一个答案?

问题描述

当我输入 1 时,ArrayList 现在有 1,然后当我重新运行代码并输入 2 时,ArrayList打印 2,但我需要的是打印 2,最后一个答案是 1。

public static void main(String[] args) {

    ArrayList<Integer> num = new ArrayList<>();
    Scanner s= new Scanner(System.in);
    int answer =s.nextInt();
    num.add(answer);
    System.out.println(num);
    System.out.println(num.size());
}

标签: javaarraylist

解决方案


每次运行这个程序时,都会创建一个新的 ArrayList 对象(显然,一个新的 ArrayList 对象是空的)。这就是为什么您看不到以前运行的输入的原因。


推荐阅读