Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you implement a boolean function in another Dynamic Array List function in Java?

This is what I’ve written so far, how do I implement prime_check into prime_array? I’m a beginner so it’d be helpful if you could keep it simple.

The question –
Write a Java function that takes as input a dynamic list and returns a dynamic list of prime numbers (you need to implement the function prime_check(int num)).

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;

    public class notes {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        ArrayList <Integer> listA2=new ArrayList<Integer(Arrays.asList(5,6,7,8,10,13,17,19,20,26,12,31));
        System.out.println(prime_array(listA2));
    } 
    
    public static boolean prime_check(int num) {
        
        boolean primecheck = true; 
        if(num <= 1) {
            primecheck = false; 
            return primecheck;
        }
        else {
            for (int i = 2; i<= num/2; i++) {
                if ((num % i) == 0) {
                    primecheck = false;  
                    break;
                }
            }
            return primecheck;
        }
        
    }

    public static ArrayList<Integer> prime_array(ArrayList<Integer> listA2) {
        
        ArrayList <Integer> nums1=new ArrayList<Integer>();
        
        for (int n1: listA2) {
            System.out.println(prime_check(n1));
            if ( = true) {
                nums1.add(n1);
            }
                
        }
        
        return nums1;
        
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You were very close to a solution. Try with this:

public static List<Integer> prime_array(List<Integer> listA2) {
    
    ArrayList <Integer> nums1=new ArrayList<Integer>();
    
    for (int n1: listA2) {
        if (prime_check(n1) == true) {
            nums1.add(n1);
        }
            
    }
    
    return nums1;
    
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading