Advertisement
Alice_Kim

Untitled

Dec 12th, 2019
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. package pgdp.iter;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Iterator;
  5.  
  6. public class Range implements Iterable<Integer>{
  7. private final int begin;
  8. private final int end;
  9. private final int stride;
  10.  
  11. public Range(int begin, int end, int stride) {
  12. this.begin = begin;
  13. this.end = end;
  14. this.stride = stride;
  15. if (stride <= 0) {
  16. Util.badArgument("Anzahl der Schritte soll größer 0 sein");
  17. }
  18. }
  19.  
  20. public Range(int begin, int end) {
  21. this.begin = begin;
  22. this.end = end;
  23. stride = 1;
  24. }
  25.  
  26. public Iterator<Integer> iterator() {
  27. ArrayList<Integer> list = new ArrayList<Integer>();
  28. if (begin == end)
  29. list.add(begin);
  30. if (begin < end) {
  31. list.add(begin);
  32. int addition = begin + stride;
  33. while (addition <= end) {
  34. list.add(addition);
  35. addition += stride;
  36. }
  37. } else {
  38. list.add(begin);
  39. int subtraction = begin - stride;
  40. while (subtraction >= end) {
  41. list.add(subtraction);
  42. subtraction -= stride;
  43. }
  44. }
  45. Iterator<Integer> iter = list.iterator();
  46. while (iter.hasNext())
  47. System.out.print(iter.next() + ", ");
  48. return iter;
  49. }
  50.  
  51. public static void main(String[] args) {
  52. Range range = new Range(14, 24, 3);
  53. Iterator<Integer> iter = range.iterator();
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement