get prime numbers and total prime numbers in range

You have to store the values, for example like this :

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class PrimeTest {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number till which the prime numbers are to be calculated: ");
        int input = scanner.nextInt();
        List<Integer> primes = new ArrayList<>();

        // loop through the numbers one by one
        for (int i = 2; i < input; i++) {
            boolean isPrimeNumber = true;

            // check to see if the number is prime
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isPrimeNumber = false;
                    break; // exit the inner for loop
                }
            }

            // print the number if prime
            if (isPrimeNumber) {
                primes.add(i);
            }
        }
        System.out.println("The number of prime is: " + primes.size() + ", and they are: " + primes.toString());
    }
}

Thank you every one for helping out.

My final code:

package com.example.test;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class PrimeTest {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number till which the prime numbers are to be calculated: ");
        int input = scanner.nextInt();
        scanner.close();
        List<Integer> primes = new ArrayList<>();

        // loop through the numbers one by one (edit include input in range)
        for (int i = 2; i <= input; i++) {
            boolean isPrimeNumber = true;

            // check to see if the number is prime
            for (int j = 2; j < i; j++) {
                if (i % j == 0) {
                    isPrimeNumber = false;
                    break; // exit the inner for loop
                }
            }

            // print the number if prime
            if (isPrimeNumber) {
                primes.add(i);
            }
        }
        String s = primes.toString().replace("[", "").replace("]", "");
        System.out.println("The number of prime is: " + primes.size() + ", and they are: " + s);
    }
}

Output:

Enter the number till which the prime numbers are to be calculated: 70
The number of prime is: 19, and they are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67

Tags:

Java