我有一个按升序排序的整数数组。我希望能够调用我的方法并按该顺序将 x 返回到第 x+y 个最高值元素。然而,我似乎无法理解逻辑应该如何查找 for(init;condition;incr/decr) 部分。
import java.lang.*;
import java.util.*;
import java.io.*;
public class test{
public static void printRangeOfInts(int x, int y) {
int[] a = {1, 2, 3, 4, 5, 6, 7};
for(int i = y-1; i >= x; --i){
System.out.println("Value:" + a[i]);
}
}
public static void main(String[] args){
System.out.println("printRangeOfInts(2,3) should print:\nValue: 6\nValue: 5");
System.out.println();
System.out.println("Prints wrong:");
printRangeOfInts(2,3);
System.out.println();
System.out.println("printRangeOfInts(1,7)should print:\nValue: 7\nValue: 6\nValue: 5\nValue: 4\nValue: 3\nValue: 2\nValue: 1");
System.out.println();
System.out.println("Prints wrong:");
printRangeOfInts(1,7);
}
}
这应该是正确的:
public static void printRangeOfInts(int x, int y) {
int[] a = { 1, 2, 3, 4, 5, 6, 7 };
for (int i = a.length - x; i >= a.length - y; i--) {
System.out.println("Value:" + a[i]);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句