I am trying to search through an array and pick out all of the unique strings meaning only one instance of each string is being printed. Then I want to them print them out. However, it is not detecting any unique strings. Could someone help me figure out what is wrong?
Note: Essentially, I am trying to count how many strings there are, without counting duplicates.
public class Test {
public static String uniquecenter;
public static void main (String[] args){
//Grab Data and Feed into Centers
String centers[]=new String[1000];
/* Only for Testing Purposes*/
centers[0] = "Table Tennis";
centers[1] = "Soccer";
centers[2]= "Baseball";
centers[3] = "Table Tennis";
//Unique Centers
String uniquecenters[]=new String [1000];
//0 out array
for(int i=0; i<1000;i++){
uniquecenters[i]="0";
}
//loop through center array
for(int i=0; i <1000; i++){
boolean unique=false;
//Loop through unique centers
for(int l=0; l<1000; l++){
//if it finds that this point in the centers array already has been indexed in the unique centers
//array then it is not unique...so move on to the next center
if(uniquecenters[l].equals(centers[i])){
unique=true;
}
}
//if it never found this string in the uniquecenters array...
if(unique==false){
//find an empty spot in the unique array
for(int l=0;l<1000;l++){
//grab the unique centers string
String c=uniquecenters[l];
//check if something is already in this spot...if not then...
if(uniquecenters.equals("0")){
//..make it a unique center
uniquecenters[l]=uniquecenter;
}//End of placing center
}//end of looking for unique spot
}//end of if it is unique
}//end of creating this unique center array
//print all unique strings
for(int i =990; i>=0;i--){
String print =uniquecenters[i];
//if it is emptry
if(print.equals("0")){
}else{
//print this unique center
System.out.println(print);
}
}
}
}
HashMap?Set. There are a number of problems with this code, but stylistically I immediately note the strange use of the word unique and the use of hard-coded limits instead ofarray.length.<String, Integer>. loop through your array, using the String as the key, and increment the value of that element in the HashMap. Then, go through the HashMap, and the keys where the value is 1 are unique.