Arrays.asList issue when computing square root of integer array elements

326 views Asked by At

I'm trying to write a code which gets a array of ints and checks if the square root of the number is in the array, if yes it will print yes else it will print no. I can't figure out why my code returns no all the time.

For example if my input is : 1 4 0 2 16 3

My output will be : yes yes yes no yes no

This is my code:

import java.util.Arrays;

public class Assignment02Q04 {
    public static void main(String[] args) {
        int[] intlist = new int[args.length]; 
        for (int i=0; i < args.length; i++) {
            intlist[i] = Integer.parseInt(args[i]);
        }

        for (int number : intlist) {
            int sqrt = (int)(Math.sqrt(number)); 
            System.out.println(sqrt); 
            if (Arrays.asList(intlist).contains(sqrt)) {
                System.out.println("yes");
            } else {
                System.out.println("no"); 
            }
        }
   }            
}
2

There are 2 answers

0
Adrian B. On BEST ANSWER

Consider using a collection from the start, instead of continuously converting, using Arrays.asList(). Also, check that the number has a natural square root by using floor on the square root and comparing it's power of 2 to the original number. Here is the code which returns the expected result yes yes yes no yes no:

public static void main(String[] args) {
    List<Integer> intlist = new ArrayList<Integer>();
    for (int i = 0; i < args.length; i++) {
        intlist.add(Integer.parseInt(args[i]));
    }

    for (int number : intlist) {
        int sqrt = (int) (Math.floor(Math.sqrt(number)));
        if (sqrt * sqrt == number && intlist.contains(sqrt)) {
            System.out.print("yes ");
        } else { 
            System.out.print("no ");
        }

    }
}
4
M A On

Arrays.asList(intlist) returns a list of arrays int[]. The int[] array itself is here treated as single object that is passed to the method:

// the return is a list of arrays; arrays are objects in Java
List<int[]> asList = Arrays.asList(intlist);

You can resolve this by using an array of Integer objects instead.

Integer[] intlist = new Integer[args.length]; 
for (int i=0; i < args.length; i++) {
    intlist[i] = Integer.parseInt(args[i]);
}