Rabbit3cat
10-25-2005, 06:02 PM
Hey
Im trying to read an undefined number of strings from a file.
Compare these and output all the strings that are the same, along with the amount of times each string occurs.
ie, for the strings: mountain lava cake mountain lava
the program would return mountain 2, lava 2, cake 1
The way i have approached this, is to read the strings from the file and store them in an array
What im not sure about is how to compare the strings, and return only one of each string, disguarding all the duplicates, then to return the number of times each string appears in the file.
Does anybody know how i could do this??
String thisLine;
int count = 0;
String s[] = new String[10];
try {
FileInputStream fin = new FileInputStream("Recipients");
BufferedReader myInput = new BufferedReader
(new InputStreamReader(fin)); int i = 0;
while (((thisLine=myInput.readLine())!=null)&&i<10) {
//add the strings to the array s
s[i] = thisLine;
System.out.println(s[i]);
count++;
//compare the strings and return all that are the same for(int index = 0; index < s.length; index++) {
for(int index1 = 0; index1 < s.length; index1++){
if((s[index].compareTo(s[index1])) == 0) {
s[index] = s[index1];
//Here i want to for each string the amount of times it occurs
}
}
}
Im trying to read an undefined number of strings from a file.
Compare these and output all the strings that are the same, along with the amount of times each string occurs.
ie, for the strings: mountain lava cake mountain lava
the program would return mountain 2, lava 2, cake 1
The way i have approached this, is to read the strings from the file and store them in an array
What im not sure about is how to compare the strings, and return only one of each string, disguarding all the duplicates, then to return the number of times each string appears in the file.
Does anybody know how i could do this??
String thisLine;
int count = 0;
String s[] = new String[10];
try {
FileInputStream fin = new FileInputStream("Recipients");
BufferedReader myInput = new BufferedReader
(new InputStreamReader(fin)); int i = 0;
while (((thisLine=myInput.readLine())!=null)&&i<10) {
//add the strings to the array s
s[i] = thisLine;
System.out.println(s[i]);
count++;
//compare the strings and return all that are the same for(int index = 0; index < s.length; index++) {
for(int index1 = 0; index1 < s.length; index1++){
if((s[index].compareTo(s[index1])) == 0) {
s[index] = s[index1];
//Here i want to for each string the amount of times it occurs
}
}
}