java - 从java中的arraylist返回所有奇数
问题描述
在构造函数中,我使用 random 函数将 20 个从 1 到 99 的随机数打印到 ArrayList(iList) 中。然后我做了一个方法,从生成到 iList 的随机数中获取所有奇数并输出奇数,但由于某种原因它没有输出奇数。有人可以帮我解决这个问题。
我的代码如下:
import java.util.*;
import java.util.Random;
public class ArrayList_Practice
{
int List;
ArrayList<Integer> iList=new ArrayList<Integer>();
Random rand = new Random();
public ArrayList_Practice() {
for(int i = 0; i < 20; i++)
{
List = rand.nextInt(100);
iList.add(List);
}
System.out.println(iList);
}
public void getoddNumber() {
int thesizeof = iList.size();
int s = 0;
for(int i = 0; i < thesizeof; i++){
if(thesizeof % 2 == 1){
thesizeof = iList.remove(iList.size()-1);
iList.remove(iList.size()-1);
System.out.println(iList);
}
}
}
}
解决方案
您比较列表的大小,而不是索引。而且因为原始列表大小甚至是你永远不会走进 if 块。
if(i % 2 == 1){
System.out.println(iList.get(i));
}
顺便说一句:你应该学习如何调试你的代码。
推荐阅读
- qt - Yocto QT5 在构建配置和自定义层的配置中复制层
- flutter - 响应式 GridView 全屏颤动
- mongodb - 使用 Spring Data 插入 MongoDB 插入两个集合
- python - BeautifulSoup 在应该拉更多的时候只拉 1 条线
- reactjs - 如何使用 react-virtualized 消除数据表边缘的闪烁?
- php - 未设置用户名中的 PHP cookie
- javascript - 如何在html中的相同onclick事件属性上调用两种不同的JavaScript函数,一种用于桌面版本,一种用于移动版本?
- python - Pycharm 类型提示类
- android - Android AlertDialog DecorView 内存泄漏
- kotlin - Kotlin 迭代一个集合并将某个值映射到新映射