From 8404cad4069499d287a5adb024de7348056cd256 Mon Sep 17 00:00:00 2001 From: SowinskiBraeden Date: Thu, 13 Mar 2025 19:01:49 -0700 Subject: [PATCH] add assignment 2 q3 --- .../bcit/comp1510/assignment2/q3/Primes.java | 107 +++++++++++++++++- 1 file changed, 102 insertions(+), 5 deletions(-) diff --git a/src/ca/bcit/comp1510/assignment2/q3/Primes.java b/src/ca/bcit/comp1510/assignment2/q3/Primes.java index 74d16d8..daad114 100644 --- a/src/ca/bcit/comp1510/assignment2/q3/Primes.java +++ b/src/ca/bcit/comp1510/assignment2/q3/Primes.java @@ -1,22 +1,119 @@ package ca.bcit.comp1510.assignment2.q3; +import java.util.List; +import java.util.ArrayList; + +import java.util.Scanner; + /** *

This is where you put your description about what this class does. You * don't have to write an essay but you should describe exactly what it does. * Describing it will help you to understand the programming problem better.

* - * @author Your Name goes here - * @version 1.0 + * @author Braeden Sowinski + * @version 1.0.0 */ public class Primes { + + /** primes list up to nth number. */ + private List primes; + + /** + * Primes constructor. + * @param n int + */ + public Primes(int n) { + primes = new ArrayList(n); + calculatePrimes(n); + } + + /** printPrimes. */ + public void printPrimes() { + for (int i = 0; i < primes.size(); i++) { + if (primes.get(i)) { + System.out.print(i + " "); + } + } + } + + /** + * countPrimes. + * @return int number of primes + * */ + public int countPrimes() { + int count = 0; + + for (int i = 0; i < primes.size(); i++) { + if (primes.get(i)) { + count++; + } + } + return count; + } + + /** + * isPrime. + * @param n int number + * @return boolean + */ + public boolean isPrime(int n) { + if (n <= 1) { + return false; + } + + for (int i = 2; i < n; i++) { + if (n % i == 0) { + return false; + } + } + + return true; + } + + /** + * calculatePrimes. + * @param n int number of primes + * */ + private void calculatePrimes(int n) { + for (int i = 0; i < n; i++) { + primes.add(isPrime(i)); + } + } + /** *

This is the main method (entry point) that gets called by the JVM.

* * @param args command line arguments. */ public static void main(String[] args) { - // your code will go here!!! - System.out.println("Question three was called and ran sucessfully."); - } + + Scanner scan = new Scanner(System.in); + + int bound = 0; + boolean valid = false; + + do { + System.out.print("Enter an upper bound: "); + if (!scan.hasNextInt()) { + System.out.println(scan.next() + " is not a valid integer.\n"); + continue; + } + + bound = scan.nextInt(); + + if (bound <= 1) { + System.out.println("Bound must be greater than 1.\n"); + continue; + } + + valid = true; + } while (!valid); + + scan.close(); + + Primes p = new Primes(bound); + + p.printPrimes(); + } }