JAVA PROGRAMMING •The owner of Sara’s Vet Clinic tracks information about her pa
ID: 3683456 • Letter: J
Question
JAVA PROGRAMMING
•The owner of Sara’s Vet Clinic tracks information about her patients to do analysis. No user data validation necessary. This data is stored in a transaction file called visits.txt. The file contains the following information # delimited:
–Animal type ( dog, cat, snake, etc.). There are an unknown number of animal types
–Animal weight.
•To help with planning the data file will not contain more than 200 entries
Sara would like a report printed to the screen listing the mean weight of all animal visits in the file and the mean by animal type. An example report is
Mean weight of all animals is 20.25
Mean weight of dogs is 35.3
Mean weight of cats is 10.5
Mean weight of snakes is 2.25
Explanation / Answer
visits.txt:
dog#22.20
cat#10.5
snack#5
elephant#100.6
cow#30.2
snack#5
snack#8.7
cow#40.2
dog#12.20
elephant#50.6
AnimalTracker.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
public class AnimalTracker {
/**
* @param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String fileName = "D:\visits.txt";
File file=new File(fileName);
if(file.exists()){
BufferedReader br1 = new BufferedReader(new FileReader(file));
BufferedReader br2 = new BufferedReader(new FileReader(file));
String sCurrentLine;
String values[];
int linecount = 0;
while ((sCurrentLine = br2.readLine()) != null) {
linecount++;
}
String animals[] = new String[linecount];
double weights[] = new double[linecount];
linecount = 0;
while ((sCurrentLine = br1.readLine()) != null) {
values = sCurrentLine.split("#");
animals[linecount] = values[0];
weights[linecount] = Double.parseDouble(values[1]);
linecount++;
}
String s[] = new HashSet<String>(Arrays.asList(animals)).toArray(new String[0]);
double individula_sum = 0;
double allanimals_sum = 0;
int count = 0;
for(int i=0; i<s.length; i++){
allanimals_sum = 0;
individula_sum = 0;
count = 0;
for(int j=0; j<animals.length; j++){
if(animals[j] != null){
if(s[i].equals(animals[j])){
individula_sum = individula_sum + weights[j];
count++;
}
allanimals_sum = allanimals_sum + weights[j];
}
}
System.out.println("Mean Weight of "+s[i]+" is : "+(individula_sum/count));
}
System.out.println("Mean Weight of all animals is : "+allanimals_sum/animals.length);
br1.close();
br2.close();
}
else{
System.out.println("File does not exist");
}
}
}
Output
Mean Weight of cat is : 10.5
Mean Weight of elephant is : 75.6
Mean Weight of cow is : 35.2
Mean Weight of dog is : 17.2
Mean Weight of snack is : 6.233333333333333
Mean Weight of all animals is : 28.52
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.