Java Arraylist 在列表中每隔一个数字打印一次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10018236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:17:18  来源:igfitidea点击:

Java Arraylist printing every other number in a list

java

提问by Nicole

This is my code for printing the random numbers in an arraylist:

这是我在数组列表中打印随机数的代码:

public void printList()
{
    System.out.println("The numbers on the list: ") ;
    for (int i = 0 ; i < aList.size() ; i++)
    {
        System.out.print( aList.get(i) + "  ") ;
    }
    System.out.println("\n") ;                
}

How would I print every other number of this same list? By using a do-while loop?

我将如何打印相同列表的所有其他数字?通过使用 do-while 循环?

回答by ahanin

Put additional if statement inside your for block which would check for parity: if (i % 2 == 0) { System.out.print(... }

在 for 块中添加额外的 if 语句,用于检查奇偶校验: if (i % 2 == 0) { System.out.print(... }

回答by horbags

Above approach is ineffecient. Just increment the index by 2

以上方法无效。只需将索引增加 2

public void print()
{
    System.out.println("The numbers on the list: ") ;
    for (int i = 0 ; i < aList.size() ; i+=2)
    {
        System.out.print( aList.get(i) + "  ") ;
    }
    System.out.println();                
}