【发布时间】:2014-04-27 22:37:54
【问题描述】:
我正在尝试搜索一个数组并挑选出所有唯一的字符串,这意味着每个字符串只打印一个实例。然后我想让他们打印出来。但是,它没有检测到任何唯一的字符串。有人可以帮我找出问题所在吗?
注意:本质上,我试图计算有多少字符串,而不计算重复项。
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的键? -
如何使用 hashmap 找到唯一的字符串?
-
@AntonH 这实际上更适合
Set。这段代码有很多问题,但从风格上看,我立即注意到独特一词的奇怪用法以及硬编码限制的使用,而不是array.length。 -
创建
<String, Integer>类型的HashMap。循环遍历您的数组,使用 String 作为键,并在 HashMap 中增加该元素的值。然后,遍历HashMap,值为1的key是唯一的。 -
@chrylis Sets 将删除字符串的第二个(和第三个等)副本,但不必说它是否唯一。或者你有一种我没有想到的方法。另外,老实说,我什至没有查看代码,所以我没有查看任何其他编程或逻辑错误。 EDIT 鉴于 OP 的编辑,是的,Sets 可能会更好。