I have a java class that includes an array of String and two for loops
for passing the elements of the array and their printing, as well as their redundancy in
since they are strings.
I want someone to help me print each element (String) once, even if it
repeated in an array.
The following code prints an element in an array more than once.
So, comparing the elements of a Needed array
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 have a solution without using .util. * package
I have a second test, but it prints one element and its 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; } }}}}
source share