简体   繁体   English

从 java 中的 arraylist 返回所有奇数

[英]Returning all Odd numbers from an arraylist in java

In the constructor I used the random function to print out 20 random numbers from 1 to 99 into the ArrayList(iList).在构造函数中,我使用随机 function 将 20 个从 1 到 99 的随机数打印到 ArrayList(iList) 中。 Then I made a method that will get all odd numbers from the random numbers that generated into iList and output the odd numbers put it isn't outputting the odd numbers for some reason.然后我做了一个方法,从生成到 iList 和 output 的随机数中获取所有奇数,奇数表示由于某种原因它没有输出奇数。 Could someone help me fix this.有人可以帮我解决这个问题。

My code below:我的代码如下:

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);
           }
        }
    }
}

You compare the sitze of the list,not the index.您比较列表的大小,而不是索引。 And because the original list size is even you never walk into the if block.而且因为原始列表大小甚至是您永远不会走进 if 块。

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

BTW: you should learn how to debug your code.顺便说一句:你应该学习如何调试你的代码。

If you want to print the odd numbers (and not the numbers at the odd indices) the you should do it like this.如果你想打印奇数(而不是奇数索引处的数字),你应该这样做。

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 + " ");
   }
}

Prints印刷

1 3 17 19

If you want the numbers at odd indices, then you don't need to test if they are odd, just print every other one starting at 1.如果您想要奇数索引处的数字,那么您不需要测试它们是否为奇数,只需从 1 开始每隔一个打印一个。

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

Prints印刷

2 10 14 18 19 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM