首页 > 解决方案 > 从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);
           }
        }
    }
}

标签: javaloopsfor-looparraylist

解决方案


您比较列表的大小,而不是索引。而且因为原始列表大小甚至是你永远不会走进 if 块。

       if(i % 2 == 1){
            System.out.println(iList.get(i));
       }  

顺便说一句:你应该学习如何调试你的代码。


推荐阅读