简体   繁体   English

在Java中按降序或升序打印整数的范围

[英]print range of integers in descending or ascending order in java

I have an upper bound and a lower bound and I want to return all number number between the bounds including the bounds. 我有一个上限和一个下限,我想返回所有界限之间的数字,包括界限。 I know python has a range function but I'm sure if java has this method. 我知道python具有范围功能,但是我确定java是否具有此方法。

You can just use a for loop. 您可以只使用for循环。 Do you want to print them or return them? 您要打印还是退回它们? Your title and question disagree on this. 您的标题和问题对此持不同意见。 If you want to return them, you will need to pick the type that you use to contain them. 如果要返回它们,则需要选择用于包含它们的类型。

List<Integer> ret = new ArrayList<Integer>();
for (int i = lower; i <= upper; i++) {
    ret.add(i);
}
return ret;

I will leave it as an exercise to print them, or to get them in descending order. 我将其作为练习打印或按降序排列。

If you have an array if integers you can use IntRange in Apache Commons Lang: 如果您有一个整数数组,则可以在Apache Commons Lang中使用IntRange

http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/IntRange.html http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/IntRange.html

IntRange ir = new IntRange(int lower, int upper);
ir.toString();

More info of the various Range's you can use here: 您可以在此处使用各种范围的更多信息:

http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/class-use/Range.html http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/math/class-use/Range.html

EDIT: I totally over-read the question. 编辑:我完全阅读问题。 I saw a suggestion of an IntRange utility and I just assumed this was the classic "I want an Iterable" request, which I hear often. 我看到了有关IntRange实用程序的建议,我只是以为这是我经常听到的经典“我想要一个可迭代”请求。 So ignore the below. 因此,请忽略以下内容。

Simplified (without error checking): 简化(无错误检查):

public static List<Integer> range(final int start, final int end) {
  return new AbstractList<Integer>() {
    public int size() {
      return end - start + 1;
    }
    public Integer get(int i) {
      return start + i;
    }
  };
}

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

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