java - 为什么我的数组列表没有保留最后一个答案?
问题描述
当我输入 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());
}
解决方案
每次运行这个程序时,都会创建一个新的 ArrayList 对象(显然,一个新的 ArrayList 对象是空的)。这就是为什么您看不到以前运行的输入的原因。
推荐阅读
- javascript - 单击分页后如何检索搜索栏上的文本
- excel - 创建一个excel vba循环以水平列出每组垂直日期的开始日期和结束日期之间的日期
- ios - 下拉隐藏导航项时刷新控件在表格视图上方留下很大间隙
- android - Burp Suite - Pixel 2 XL (Android P) 找不到使用 Burp Suite 进行证书的方法
- airflow - 安装气流时出错:默认情况下,Airflow 的依赖项之一安装 GPL
- ios - iOS 如何重新启动应用程序以更改语言 Swift 4
- r - 为什么用线条填充 SpatialLinesDataFrame 会引发错误?
- java - Lombok、Spring mongodb 和 jackson 构造函数问题
- cron - Airflow 安排任务在每月 15 号之前的星期一运行
- gemfire - 仅当 value.status 为“XXX”时才更新区域中的值