doesitmatter
doesitmatter

Reputation: 17

error converting array to string

so my program prints an array but when it does it also includes brackets and commas and i dont want those.

here is my library

import java.util.*;
public class library2
{
        public static boolean IsPrime(int p)
        {
                for (int i = 2; i < p; i++)
                {
                        if (p % i == 0 && i != p)
                                return false;
                }
                return true;
        }
        public static List<List<Integer>> GetPrimes(int n)
        {
                List<Integer> arr = new ArrayList<Integer>();
                for (int j = 2; j < n; j++)
                {
                        if(IsPrime(j))
                        {
                                arr.add(j);
                        }
                }
                return Arrays.asList(arr);
        }
}

here is my driver

import java.util.Scanner;
import java.util.*;
import java.util.Arrays;
public class driver2
{
        public static void main(String[] args)
        {
                Scanner scan = new Scanner(System.in);
                System.out.print("Please input an integer: ");
                int n = scan.nextInt();
                Boolean check = library2.IsPrime(n);
                List<List<Integer>> arr = library2.GetPrimes(n);
                System.out.println(Arrays.toString(arr));
        }
}

ive tried the Arrays.toString(); method but i get an error when i compile. i used import java.util.Arrays; but that didnt solve anything. can someone help me out.

Upvotes: 0

Views: 77

Answers (1)

griffon vulture
griffon vulture

Reputation: 6774

arr is a list and not an array.

You should iterate over and print:

     Iterator<List<Integer>>  arrIterator = arr.iterator(); 
     while (arrIterator.hasNext()) {
        List<Integer> l = arrIterator.next();
        Iterator<Integer> lIterator = l.iterator(); 
        while(lIterator.hasNext()){
          int i = lIterator.next();     
          System.out.print(i + " ");
        }
        System.out.print("\n");
    }

Upvotes: 1

Related Questions