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));
}
}
>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.