我正在尝试搜索数组并选出所有唯一字符串,这意味着每个字符串只打印一个实例。然后我想让他们打印出来。但是,它没有检测到任何唯一的字符串。有人能帮我弄清楚出了什么问题吗?
注意:基本上,我正在尝试计算有多少字符串,而不计算重复项。
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);
}
}
}
}
答案 0 :(得分:2)
您可以使用Set
,根据定义,它不包含重复项:
String centers[];
...
List<String> centerList = Arrays.asList(centers);
Set<String> uniqueCenters = new HashSet<String>();
uniqueCenters.addAll(centerList);
uniqueCenters.remove(null);
Integer numberOfUniqueStrings = uniqueCenters.size();