add assignment 2 q3

This commit is contained in:
SowinskiBraeden committed 2025-03-13 19:01:49 -07:00
1 parent 8e51f5c602
commit 8404cad406
1 file changed
+101 -4
+101 -4
View File
@@ -1,22 +1,119 @@
package ca.bcit.comp1510.assignment2.q3;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
/**
* <p>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.</p>
*
* @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<Boolean> primes;
/**
* Primes constructor.
* @param n int
*/
public Primes(int n) {
primes = new ArrayList<Boolean>(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));
}
}
/**
* <p>This is the main method (entry point) that gets called by the JVM.</p>
*
* @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();
}
}