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);
}
}
}
Please Is there any solution without using .util.* package
I have a second trial but it out prints the one element and it redundancy
only.
public class Javafool {
static String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khalo","Valderama"};
static String str2[] = new String[myArray.length];
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;
sort(myArray);
int no_of_repeat=1;
String temp =null;
int i ;
for( i = 0;i<myArray.length-1;i++)
{
temp = myArray[i];
myArray[i] = myArray[i+1];
myArray[i+1] = temp;
if(myArray[i].equals(temp))
{
no_of_repeat= ++no_of_repeat;
}
}
System.out.println(myArray[i]+""+temp+"\t"+"\t\t"+no_of_repeat);
}
public static void sort(String [] array) {
String temp = null;
for(int j=0;j<array.length;j++)
{
for(int i = 0; i<array.length-1;i++)
{
if(array[i].compareTo(array[i+1])<0)
{
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}}}}
java.util.*package? I see some solutions without it (manual sorting?) but it is nearly equivalent as the methods exposed injava.utiland it will likely be error prone.