Monday, 9 September 2013

Printing elements of an array without repeating an element

Printing elements of an array without repeating an element

I have a java class which involves a String array and two for loops
for going through the array elements and prints them plus their redundancy
in the
array as they are Strings .
I want someone help me to print each element (String) one time only even it
repeated in the array.
The following code prints some element in the array more than one time.
So comparison between elements of the array Needed
public class myClassName {
static String [] myArray =
{"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled"};
public static String [] getArray()
{
String str[] = new String[myArray.length];
for(int i=0;i<myArray.length;i++)
{
str[i] = myArray[i].toString();
}
return str;
}
public static void main( String [] args)
{
String d [] = getArray();
int noOftimesRepeated;
for(int i=0;i<getArray().length;i++)
{
noOftimesRepeated=1;
String currentName = d[i];
for(int j=0;j<getArray().length;j++)
{
if(i!=j && d[i].equalsIgnoreCase(d[j]))
{
noOftimesRepeated = noOftimesRepeated+1;
}
}
int j =0;
System.out.println(d[i]+"\t" +"\t"+noOftimesRepeated);
}
}
}

No comments:

Post a Comment