-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEx6.java
More file actions
43 lines (36 loc) · 1.21 KB
/
Ex6.java
File metadata and controls
43 lines (36 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package java_exercises_1_sda;
//Dla zadanej tablicy intów policz ile jest w niej liczb ujemnych. Jeśli takie występują
// utwórz nową tablicę, do której przepisze tylko te ujemne liczby
public class Ex6 {
public static void main(String[] args) {
int[] numbers = {99, -1, 0, 2, -44, -5, 44};
tablePrint(numbers);
int[] negatives = storeNegativesInNewArray(numbers);
tablePrint(negatives);
}
public static int getNegatives(int[] numbers) {
int negativeCount = 0;
for (int number : numbers) {
if (number < 0) negativeCount++;
}
return negativeCount;
}
public static int[] storeNegativesInNewArray(int[] numbers) {
int size = getNegatives(numbers);
int[] negativesArray = new int[size];
int iterator = 0;
for (int number : numbers) {
if (number < 0) {
negativesArray[iterator] = number;
iterator++;
}
}
return negativesArray;
}
public static void tablePrint(int[] array) {
for (int index : array) {
System.out.println("[" + index + "] ");
}
System.out.println("");
}
}