mercredi 9 novembre 2016

How do you test for an empty array?

I have been creating this java programme where its finds duplicates in an array and is able to give the positions of the duplicates.

Here is the code

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // String to list 
    String foxes = "The,Quick,Brown,Fox,Jumps,Over,The,Lazy,Dog."; //*creates string
    System.out.println(" Here is the string unedited: " + foxes); //prints string
    String lowerCase = foxes.toLowerCase() .replaceAll("[\.:;'\"!\?]", " "); //remove punctuation + sets to lower case
    System.out.println(" Here is the string (no caps + no punctuation): " + lowerCase); //prints no punctuation

    List<String> foxesList = new ArrayList<String>(Arrays.asList(lowerCase.split(","))); //converts string into array

Map<String, ArrayList<Integer>> map = new HashMap<>(); //creates new hashmap and array
        for (int i = 0; i < foxesList.size(); i++) { //loops through array
        String fox = foxesList.get(i); //gets the duplicate + its postion
        ArrayList<Integer> list = map.get(fox); //gets duplicate integer

        if (list == null) {
         list = new ArrayList<>(); //creates new list
         list.add(i); //adds duplicate positon to array
          map.put(fox, list); //adds lists/arrays to map
        } else { //else
         list.add(i); //adds duplicate to list 
         System.out.println(" The duplicate was: [" + fox + "] In the positions: " + list); //prints duplicates as well as duplicate postions
        }

        String empty = fox.replaceAll("[\.:;'\"!\?],", " ");
        List<String> emptyfox = new ArrayList<String>(Arrays.asList(empty.split("")));

        if (emptyfox == null) {
         System.err.println("array is empty");
        } else {
         System.err.println("System contains duplicate");
        } 
    }
}      

}

There is an issue with the code, the final stage i am trying to get the system to print when the array has a duplicate. It currently prints this many times (this is because of the nested loops) and it does not correctly print if it is empty. I have removed the square brackets and commas to check it however, it still doesnt work. Here is the code that does not work:

String empty = fox.replaceAll("[\.:;'\"!\?],", " ");
        List<String> emptyfox = new ArrayList<String>(Arrays.asList(empty.split("")));

        if (emptyfox == null) {
         System.err.println("array is empty");
        } else {
         System.err.println("System contains duplicate");

I hope that you can help!

Aucun commentaire:

Enregistrer un commentaire