import java.util.ArrayList;
class PrimeDirective {
int i;
boolean num;
int number;
// Add your methods here:
public boolean isPrime(int number) {
if (number == 2) {
num = true;
}
else if (number < 2) {
num = false;
}
for (i = 2; i < number; i++) {
if (number % i == 0) {
num = false;
}
else {
num = true;
}
}
return num;
}
public ArrayList<Integer> onlyPrimes(int[] numbers) {
ArrayList<Integer> primes = new ArrayList<Integer>();
for (int number : numbers) {
if (isPrime(number)) {
primes.add(number);
}
}
return primes;
}
public static void main (String[]args){
PrimeDirective pd = new PrimeDirective();
int[] numbers = {6, 29, 28, 33, 11, 100, 101, 43, 89};
System.out.println(pd.isPrime(6));
System.out.println(pd.onlyPrimes(numbers));
}
}
This prints: true, and numbers
Note: I had to made the num a boolean value and return num because my system was not recognizing my return statements. Maybe the problems are related?
I had a similar issue, although I am not sure this is the best way to solve this problem, I felt the true statements within the for loop as it counted through all of the possibilities, was at some point overwriting the value.
While I can’t 100% pinpoint what I had done wrong, this was my issue.
While I was getting the onlyPrime method to work as intended, the program would fail when the numbers was ran through the isPrime.
I solved this by deciding all values were true until proven false (the judicial system was the idea) which was different then how codecademy was explaining it in the hints. It made little sense to me regarding their logic at this point and was never successful getting this to work.
I created a variable called primeAnswer = true and then if any of the if statements below matched it would change the value to false, and the method would return the prime answer after each iteration.
// Import statement:
import java.util.ArrayList;
class PrimeDirective {
// Add your methods here
public boolean isPrime(int number){
boolean primeAnswer = true;
if (number < 2) {
primeAnswer = false;
return primeAnswer;
}
for (int i = 2; i < number; i++){
if (number % i == 0) {
primeAnswer = false;
return primeAnswer;
}
}
return primeAnswer;
}
public ArrayList<Integer> onlyPrimes(int[] numbers) {
//Declaration of Array
ArrayList<Integer> primes = new ArrayList<Integer>();
//add to Array List if True
for (int number : numbers) {
if (isPrime(number)) {
primes.add(number);
}
}
return primes;
}
// MAIN METHOD
public static void main(String[] args) {
PrimeDirective pd = new PrimeDirective();
int[] numbers = {6, 29, 28, 33, 11, 100, 101, 43, 89, 1, 31, 17};
System.out.println(pd.isPrime(7));
System.out.println(pd.isPrime(28));
System.out.println(pd.isPrime(2));
System.out.println(pd.isPrime(0));
System.out.println(pd.onlyPrimes(numbers));
}
}
See image below of output (I also modified my code to add more numbers in the numbers to further test my code.