forked from harambeisnotdead/java-carande
-
Notifications
You must be signed in to change notification settings - Fork 0
/
array.java
52 lines (38 loc) · 1.37 KB
/
array.java
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
44
45
46
47
48
49
50
51
52
import java.util.Scanner;
class array {
public static void main(String[] args) {
contarPar(fillArray(introducir()));
}
public static int introducir() { // introducir longitud array y lo devuelve
Scanner scanner = new Scanner(System.in);
try { // controla InputMismatchException con un try, catch
System.out.print("Introduce longitud array: ");
return scanner.nextInt();
} catch (java.util.InputMismatchException e) { return introducir(); }
}
public static int[] fillArray(int n) { // rellena el array con numeros aleatorios
int[] a = new int[n]; // declara el array con longitud n
System.out.print("\nArray --> ");
for (int i = 0 ; i < n ; i++) {
a[i] = (int) (Math.random() * 101);
System.out.print(a[i] + " ");
}
return a;
}
public static void contarPar(int[] a) { //cuenta los numeros pares e impares del array
int par = 0, impar = 0;
String parS = "", imparS = "";
for (int i = 0 ; i < a.length ; i++) {
if (a[i]%2==0) {
par++;
parS += a[i] + " ";
} else {
impar++;
imparS += a[i] + " ";
}
}
// muestra los resultados
System.out.println("\n\nPares: " + par + " --> " + (float) par/a.length * 100 + "%" + " --> "+ parS);
System.out.println("Impares: " + impar + " --> " + (float) impar/a.length * 100 + "%" + " --> " + imparS + "\n");
}
}