仅打印给定数字范围内的数组成员

时间:2019-06-20 16:16:11

标签: java

        ArrayList<Integer> luvut = new ArrayList<>();
        luvut.add(3);
        luvut.add(2);
        luvut.add(6);
        luvut.add(-1);
        luvut.add(5);
        luvut.add(1);
        tulostaRajatutLuvut(luvut, 0, 5);
    }
    public static void tulostaRajatutLuvut(ArrayList<Integer> luvut, int alaraja, int ylaraja) {

        int i = 0;
        while (alaraja <= ylaraja) {
             if (luvut.get(i) >= alaraja && luvut.get(i) <= ylaraja) {
                 System.out.println(luvut.get(i));
            }
            i++;
        }
    }
}

该代码可以正常工作,但最终会中断,不确定为什么。应该从给定数字之间的数组中打印数字。其次,这甚至是执行此操作的好方法吗?

1 个答案:

答案 0 :(得分:1)

考虑使用增强的for循环/ for-each循环而不是while循环,因此您不必担心手动递增i变量等。

import java.util.ArrayList;
import java.util.List;

class Main {
  public static void main(String[] args) {
    List<Integer> numbersList = new ArrayList<>();
    numbersList.add(3);
    numbersList.add(2);
    numbersList.add(6);
    numbersList.add(-1);
    numbersList.add(5);
    numbersList.add(1);
    System.out.printf("Numbers List: %s%n", numbersList);
    int start = 0;
    int end = 5;
    List<Integer> numbersBetweenList = numbersBetweenInclusive(numbersList, start, end);
    System.out.printf("Numbers Between %d and %d (inclusive): %s%n", start, end, numbersBetweenList);
  }

  public static List<Integer> numbersBetweenInclusive(List<Integer> numbersList, int start, int end) {
    List<Integer> result = new ArrayList<>();
    for (int num : numbersList) {
      if (num >= start && num <= end) {
        result.add(num);
      }
    }
    return result;
  }

}

输出:

Numbers List: [3, 2, 6, -1, 5, 1]
Numbers Between 0 and 5 (inclusive): [3, 2, 5, 1]