Click to See Complete Forum and Search --> : Java array help
philortals
04-15-2005, 06:51 PM
Hello,
If if have an array of strings, let say,
String animals[] = { "dog", "cat", "dog", "dog", "horse", "cat" };
Is there a way to count how many times each element is listed and then print the total for each element.
Any help would be great.
Thank You.
Khalid Ali
04-16-2005, 09:12 AM
not really, wht you will need to do is create another array thats length is of the same as the string arrays length.
THen you go through the string array as many times for second array and see if the value at an indexin the string array is repeated.
However, if you use List objects this process becomes allot easier
philortals
04-16-2005, 11:23 AM
Could you maybe give me an example of what you mean. I am new to java and need as much explanation as possible.
Thanks for you help.
Philip
ray326
04-16-2005, 02:36 PM
Learn about a for() loop.
Khalid Ali
04-16-2005, 07:04 PM
well I had some free time on hand, here is a sample program, that I think will do what you want to get done.
public class DuplicateValuesInArray {
/**
*
*/
public DuplicateValuesInArray(){
String[] animals = { "dog", "cat", "dog", "dog", "horse", "cat" };
String[] dupliArr = new String[animals.length];
int len = animals.length;
int duplicateCtr=0;
for(int n=0;n<len;n++){
String word = animals[n];
int ctr=0;
for(int x=0;x<len;x++){
if(word.equals(animals[x])){
ctr++;
}
}
if(!isPresent(word, dupliArr)){
dupliArr[duplicateCtr++] = "word ["+word+"],"+ctr+"\ttimes";
}
}
printResults(dupliArr);
}
/**
*
* @param word
* @param dupliArr
* @return
*/
public boolean isPresent(String word, String[] dupliArr){
int len = dupliArr.length;
for(int x=0;x<len;x++){
if(null!=dupliArr[x] && dupliArr[x].indexOf(word)>-1){
return true;
}
}
return false;
}
/**
*
* @param dupliArr
*/
public void printResults(String[] dupliArr){
int len = dupliArr.length;
for(int x=0;x<len;x++){
if(null!=dupliArr[x])
System.out.println(dupliArr[x]);
}
}
public static void main(String[] args){
new DuplicateValuesInArray();
}
}
7stud
04-17-2005, 01:08 AM
well I had some free time on hand, here is a sample program,
What's the point of posting the code for someone's homework assignment?
Khalid Ali
04-17-2005, 01:41 AM
keep on looking for a point in it(apparently you have even more time on hand then I did)