0

import java.util.HashSet;

import java.util.Scanner;

import java.util.Set;

public class PrimeNumbersFilter {

public static void main(String[] args) throws P1Exception {
    int numberCount = new Scanner(System.in).nextInt();
    int[] primeNumbers = filterPrimeNumbers(generate(numberCount));
    for (int primeNumber : primeNumbers) System.out.print(primeNumber + " ");
}

public static int[] generate(int numberCount) throws P1Exception {
    if (numberCount <= 0) throw new P1Exception();
    int[] numbers = new int[numberCount];
    for (int i = 0; i < numbers.length; i++) numbers[i] = (int) (Math.random() * (1000) + 1);
    return numbers;
}

public static int[] filterPrimeNumbers(int[] numbers) throws P1Exception {
    Set<Integer> primeNumbers = new HashSet<>();
    for (int number : numbers) {
        if (isPrime(number))
            primeNumbers.add(number);
    }
    int[] primeNumbersArray = new int[primeNumbers.size()];
    int i = 0;
    for (int primeNumber : primeNumbers) {
        primeNumbersArray[i] = primeNumber;
        i++;
    }
    return primeNumbersArray;
}

private static boolean isPrime(int number) throws P1Exception {
    if (number < 0) throw new P1Exception();
    boolean isPrime = true;
    for (int i = 2; i < number / 2; i++) {
        if (number % i == 0) {
            isPrime = false;
            break;
        }
    }
    return isPrime;
}

static class P1Exception extends Exception {

    public P1Exception() {
        System.err.println("Invalid number.");
    }
}

}

Bei der Erzeugung der zufälligen Zahlen, musst du die Implementierung so ändern, wie sie gewünscht ist, also das Muster mit den Lottozahlen aus der Vorlesung (siehe Aufgabentext)

Diese Antwort melden
geantwortet

Schüler, Punkte: 450

 

Kommentar schreiben