Spaces:
Running
Running
| Write the method | |
| ArrayList<Integer> createList(int start, int end) | |
| ...which takes as parameters the start and end values of the list. | |
| The method generates a new list containing, in order, all the elements between the given points, one step apart. | |
| As usual, the START sub-item is INCLUDED in the list, but the END sub-item IS NOT. | |
| Note that the list must be created BACKWARDS IF the STARTING sub-item is GREATER than the ending sub-item. | |
| See the sample performances for an example. | |
| Examples on method calls: | |
| public static void main(String[] parameters){ | |
| System.out.println(createList(1,10)); | |
| System.out.println(createList(10,1)); | |
| } | |
| Program outputs: | |
| [] | |
| [] | |
| =============================== | |
| import java.util.Random; | |
| import java.util.ArrayList; | |
| public class Test{ | |
| public static void main(String[] args){ | |
| final Random r = new Random(); | |
| Object[][] p = {{1,4}, {100,106}, {5,0}, {90,80}}; | |
| for (Object[] pa : p) { | |
| System.out.print("Testing with parameters "); | |
| System.out.println(pa[0] + ", " + pa[1]); | |
| System.out.println(createList((Integer) pa[0], (Integer) pa[1])); | |
| System.out.println(""); | |
| } | |
| } | |
| public static ArrayList<Integer> createList(int start, int end) { | |
| ArrayList<Integer> list = new ArrayList<>(); | |
| // ascending order | |
| if (start < end) { | |
| for (int i = start; i < end; i++) { | |
| list.add(i); | |
| } | |
| } | |
| // start > end | |
| // descending order | |
| // start >> start-1 >> ... >> (excluding) 'end' | |
| else { | |
| for (int i = start; i > end; i--) { | |
| list.add(i); | |
| } | |
| } | |
| return list; | |
| } | |
| } | |
| Testing with parameters 1, 4 | |
| [] | |
| Testing with parameters 100, 106 | |
| [] | |
| Testing with parameters 5, 0 | |
| [] | |
| Testing with parameters 90, 80 | |
| [] | |