Spaces:
Running
Running
| The program has a preformatted list variable numbers, which points to an integer-type list. | |
| Your task is to count how many negative and how many positive elements there are in the list. | |
| Print the result as shown in the example below: | |
| Example execution: | |
| Positives: 10 | |
| Negatives: 6 | |
| import java.util.Random; | |
| import java.util.ArrayList; | |
| public class Test{ | |
| public static void main(String[] args){ | |
| final Random rnd = new Random(); | |
| for (int test=1; test<=3; test++) { | |
| System.out.println("Test number " + test); | |
| // initialise an Integer list | |
| ArrayList<Integer> numbers = new ArrayList<>(); | |
| // random int from 0 to 15 (excluding 15) | |
| // add 10 to it: 10-24 | |
| int length = 10 + rnd.nextInt(15); | |
| // for the 10-24 integers | |
| // random int from 0 to 30 (excluding 30) | |
| // each element = 15 - rand_int_0_uptobutnotincl30 | |
| for (int i=0; i<length; i++) { | |
| numbers.add(15 - rnd.nextInt(30)); | |
| } | |
| System.out.println("List: " + numbers); | |
| //ADD | |
| int pos=0; | |
| int neg=0; | |
| for (int num: numbers) { | |
| if (num>0) { | |
| pos++; | |
| } | |
| else if (num<0) { | |
| neg++; | |
| } | |
| } | |
| System.out.println("Positives: " + pos); | |
| System.out.println("Negatives: " + neg); | |
| System.out.println(""); | |
| } | |
| } | |
| } | |
| Test number 1 | |
| List: [5, 7, 7, -13, 11, -13, 11, -3, -2, 6, 0, 14, 1, 13, -6, 6, -8, 15, -13, -10, 6] | |
| Positives: 12 | |
| Negatives: 8 | |
| Test number 2 | |
| List: [-13, 6, 7, -7, 9, -6, 0, -7, -8, -13, 6, -9, -10, -10, -10, 10, -7, -2, -5, -8, 13, -8, 9, -12] | |
| Positives: 7 | |
| Negatives: 16 | |
| Test number 3 | |
| List: [-14, 12, 15, 0, -2, -1, 7, 13, 14, 11, -4, 1, 9, 3, 1] | |
| Positives: 10 | |
| Negatives: 4 | |