本文翻譯自stackoverflow,by:王奎
問題:我有一個數組:
[1,2,3,6,7, 8, 9,20, 22]
我想讓它對用戶以下形式顯示
Numbers 1 through 3, 6 through 9, 20, 22
下面是一個完整是程序:
/**
blog:http://www.marksaas.com
author :marksaas
*/
public class ArrayTest{
public static void main(String[] args){
Integer[] A = {1, 2, 3, 6, 7, 8, 9, 20, 22};
System.out.print("Numbers ");
int start = 0, end;
while(start < A.length){
System.out.print(A[start]);
end = start;
while(end + 1 < A.length && A[end + 1] == A[end] + 1)
end++;
System.out.print((end == start ? "":(" through " + A[end])) + ", ");
start = end + 1;
}
}
}
歡迎關注我的微博
,我的微博會實時更新文章。 交流羣: