在java中从arraylist返回所有奇数

e0bqpujr  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(469)

在构造函数中,我使用random函数将从1到99的20个随机数打印到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);
           }
        }
    }
}
hxzsmxv2

hxzsmxv21#

比较列表的位置,而不是索引。因为原来的列表大小是偶数,所以你永远不会走进if块。

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

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

jw5wzhpr

jw5wzhpr2#

如果要打印奇数(而不是奇数索引处的数字),应该这样做。

List<Integer> list = List.of(1,2,3,10,12,14,17,18,20,19);
for(int val : list) {
   if (val % 2 == 1) {
      System.out.print(val + " ");
   }
}

印刷品

1 3 17 19

如果你想在奇数索引的数字,那么你不需要测试他们是否奇数,只要打印每一个从1开始。

for (int k = 1; k < list.size(); k+=2) {
            System.out.print(list.get(k));
}

印刷品

2 10 14 18 19

相关问题