📜  在 java 代码示例中打印素数

📅  最后修改于: 2022-03-11 14:52:33.194000             🧑  作者: Mango

代码示例2
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
 
public class PrimeNumberChecker3 {
 
    public static List generatePrimeInRange(int startRange, int endRange) {
        if (startRange >= endRange) {
            System.out.println("endRange must be greater then startRange");
            System.exit(0);
        }
        List primeList = new ArrayList<>();
        while (startRange <= endRange) {
            int i = 2, count = 0;
            while (i <= startRange / 2) {
                if (startRange % i == 0) {
                    count++;
                    break;
                }
                i++;
 
            }
            if (count == 0) {
                primeList.add(startRange);
            }
            startRange++;
        }
        return primeList;
    }
 
    public static void main(String[] args) {
        System.out.println("Enter a number range to generate prime numbers in between");
        Scanner scanner = new Scanner(System.in);
        int number1 = scanner.nextInt();
        int number2 = scanner.nextInt();
        List primeNumbers = generatePrimeInRange(number1, number2);
        System.out.println("Prime Numbers are");
        System.out.println(primeNumbers);
 
    }
}