Gyakorlati alapok
Válogatások
Kiválogatás kiírással
Magukat a kiválogatott elemeket keressük. Az értékadásnál tehát a konkrét, a feltételnek megfelelő elemet adjuk át (tombEredmeny[i] = tomb[i]).
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
int[] tomb = new int[10];
for(int i = 0; i < tomb.length; i++){
tomb[i] = random.nextInt(50) + 1;
System.out.print(tomb[i] + " ");
}
System.out.println();
int[] tombEredmeny = new int[tomb.length];
for(int i = 0; i < tomb.length; i++){
if(tomb[i] % 2 == 0){
tombEredmeny[i]
= tomb[i];
}
System.out.print(tombEredmeny[i] + "
");
}
}
}
Végeredmény (például):
31 3 37 30 43 50 29 1 30 3
0 0 0 30 0 50 0 0 30 0
Némi probléma a végeredmények kiírásánál tapasztalható, hiszen az eredménytömb 0-val inicializált elemei is kiírásra kerültek. Az eredménytömb statikus méretével nem tudunk mit kezdeni, mert nem látjuk előre, hogy hány elemet tudunk az alaptömbből kiválogatni. Azonban a 0 értékeket el tudjuk tüntetni: csakis akkor írjuk ki az eredménytömb elemeit, ha az nem 0:
if(tombMasolat[i] != 0){
System.out.print(tombMasolat[i] + " ");
}
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
int[] tomb = new int[10];
for(int i = 0; i < tomb.length; i++){
tomb[i] = random.nextInt(50) + 1;
System.out.print(tomb[i] + " ");
}
System.out.println();
int[] tombMasolat = new int[tomb.length];
for(int i = 0; i < tomb.length; i++){
if(tomb[i] % 2 == 0){
tombMasolat[i]
= tomb[i];
}
if(tombMasolat[i] != 0){
System.out.print(tombMasolat[i] + " ");
}
}
}
}
Végeredmény (például):
18 21 41 45 37 47 23 11 21 22
18 22
Vagy kissé másként:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random();
int[] tomb = new int[10];
for(int i = 0; i < tomb.length; i++){
tomb[i] = random.nextInt(50) + 1;
System.out.print(tomb[i] + " ");
}
System.out.println();
int[] tombMasolat = new int[tomb.length];
for(int i = 0; i < tomb.length; i++){
if(tomb[i] % 2 == 0){
tombMasolat[i]
= tomb[i];
System.out.print(tombMasolat[i] + " ");
}
}
}
}
Végeredmény (például):
10 19 37 47 31 24 10 15 35 36
10 24 10 36