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

Finding Perfect Squares from an ArrayList

I am trying to write code in java to find all numbers that are perfect squares from an array list and print out each number that is a perfect square in a new list, but I am getting incorrect outputs. Can you please help?

This is my code so far:

import java.util.Scanner;
import java.util.ArrayList;
public class MakeALibraryProject {
    public static ArrayList<Integer> perfectSquares(ArrayList<Integer> nums, double sqrt) {
        //Parameters: The list of the numbers 1-1000.
        for (int i = 1; i <= 1000; i++) {
            nums.add(i);
        }
        System.out.println(nums);
        //Return value: Returns all numbers from the list that are perfect squares.
        for (int i = nums.size() - 1; i >= 0; i--)  {
            sqrt = Math.sqrt(i);
            if (!(Math.floor(sqrt) == Math.ceil(sqrt))) {
                nums.remove(i);
            }
        }
        return nums;
    }
    public static void main(String[] args) {
        //Variable initialization
        ArrayList<Integer> nums = new ArrayList<Integer>();
        double sqrt = 0;
        //Function call
        System.out.println(perfectSquares(nums, sqrt));
    }
}

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 :

The issue is on the line

sqrt = Math.sqrt(i);

You aren’t checking the number you put in the list, but the index of the number. Replace it with

sqrt = Math.sqrt(nums.get(i));

and you’ll get what you expect.

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