creating a method that calculates averages from an array (java) - java

Write a static method named calculateAverageWeight, to be added to the Bowl class, which is passed an array of Bowl objects, and returns the average weight of the Bowls in the array.
this is the Bowl class:
public class Bowl {
private double weight;
private boolean empty;
private String origin; // country of manufacture
public Bowl(double w, boolean e, String origin) {
weight = w;
empty = e;
this.origin = origin;
}
public double getWeight() {
return weight;
}
public boolean getEmpty() {
return empty;
}
public String getOrigin() {
return origin;
}
public void setEmpty(boolean emptyStatus) {
empty = emptyStatus;
}
public String toString() {
return ("from " + origin + " weight: " + weight);
}
The following code worked:
public static double calculateAverageWeight(Bowl[] bowls)
{
double sum=0;
double average=0;
for(int j=0; j<bowls.length; j++)
{
sum+=bowls[j].getWeight();
average=sum/bowls.length;
}
return average;
}
but I don't understand why my most recent code didn't as they seem to run almost identically to me?:
public static double calculateAverageWeight(Bowl[] bowls){
double sum=0;
double k=bowls.length;
for(int j=0; j<bowls.length; j++){
sum=sum+bowls[j].getWeight();}
double average=sum/k;
return average;}

The code for the calculateAverageWeight is OK, but you're missing a "}" at the end of the Bowl class.
Also, your calculateAverageWeight method must be inside another class, so you may be missing something there too. May you post your code ?

public static double calculateAverageWeight(Bowl[] bowls)
{
double sum=0;
double average=0;
for(int j=0; j<bowls.length; j++)
{
sum+=bowls[j].getWeight();
average=sum/bowls.length;
}
return average;
}

Related

How to make a selection sort without using the compare() method in java?

Greetings StackOverFlow Community!
I have recently started studying java at school, and one of the assignments is to create a sorting method, like selection sort or insertion sort, without using java's own built-in functions. I have looked online a lot, and all of the methods I have found are for Arrays and not ArrayLists. The goal with the assignment is to sort a dog class after tail length, and if the dogs have the same tail length, to also sort after name.
So far this is what I have done;
Dog Class
public class Dog {
private static final double DEFAULT_TAIL_SIZE = 10.0;
private static final double DEFAULT_TAX_SIZE = 3.7;
private static int count;
private String name;
private String breed;
private int age;
private int weight;
private double tailLenght;
public Dog(String name, String breed, int age, int weight) {
//count++;
this.name = name;
this.age = age;
this.breed = breed;
this.weight = weight;
this.tailLenght = tailLenght;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getBreed() {
return breed;
}
public int getWeight() {
return weight;
}
public void setAge(int age) {
age = age <= 0 ? 1 : age;
}
public double getTailLength() {
if (breed.equals("Tax") || breed.equals("dachshund")||breed.equals("tax") || breed.equals("Dachshund")) {
return tailLenght = DEFAULT_TAX_SIZE;
} else {
return tailLenght = age * weight/DEFAULT_TAIL_SIZE;
}
}
#Override
public String toString() {
//System.out.println(String.format("name=%s breed=%s age=%d weight=%d taillenght=%.1f", name, breed, age, weight, getTailLength()));
return name + " " + breed + " " + age + " " + weight + " " + getTailLength();
}
And this is the sorting code I have made, that was not accepted due to the code using in-built java sorting methods. This is the only code I'm allowed to edit during this assignment
public class DogSorter {
public void sort(ArrayList<Dog> dogs) {
dogs.sort(new Comparator<Dog>() {
#Override
public int compare(Dog d1, Dog d2) {
int comparison = 0;
comparison = Double.valueOf(d1.getTailLength()).compareTo(d2.getTailLength());
if (comparison == 0) {
comparison = String.valueOf(d1.getName()).compareTo(d2.getName());
}
return comparison;
}
});
}
And lastly this is the runner code we received from our teachers
import java.util.ArrayList;
import java.util.Random;
public class DogSorterRunner {
private static final int NUMBER_OF_DOGS = 12;
private static final Random RND = new Random();
private static final String[] NAMES = { "Fido", "Karo", "Molly", "Bella", "Wilma", "Doris", "Sigge", "Charlie",
"Ludde", "Bamse", "Lassie", "Ronja", "Ratata", "Maki", "Dora", "Luna", "Spike", "Mumsan", "Cherie" };
private static final String[] BREEDS = { "Labrador", "Golden retriever", "Tax", "Dachshund" };
private static String getRandomValueFromArray(String[] array) {
return array[RND.nextInt(array.length)];
}
private static String randomName() {
return getRandomValueFromArray(NAMES);
}
private static String randomBreed() {
return getRandomValueFromArray(BREEDS);
}
private static int randomNumber() {
return RND.nextInt(10) + 1;
}
public static void main(String[] args) {
ArrayList<Dog> dogs = new ArrayList<>();
for (int n = 0; n < NUMBER_OF_DOGS; n++) {
Dog dog = new Dog(randomName(), randomBreed(), randomNumber(), randomNumber());
dogs.add(dog);
}
new DogSorter().sort(dogs);
for (Dog dog : dogs) {
System.out.println(dog);
}
}
Any help and feedback would be greatly appreciated!
The point of the assignment is that you should implement selection or insertion sort by yourself instead of using Java's built-in sort function. That is how you show some knowledge in implementing sorting algorithms.
Here is an example of a selection sort, which is based on your conditions (tail & name) and should give you a feeling of how the functions should look like. To do some more exercise, I suggest that you try to implement insertion sort by yourself.
public class DogSorter {
public void sort(ArrayList<Dog> dogs) {
dogs.sort(new Comparator<Dog>() {
#Override
public int compare(Dog d1, Dog d2) {
int comparison = 0;
comparison = Double
.valueOf(d1.getTailLength())
.compareTo(d2.getTailLength());
if (comparison == 0) {
comparison = String
.valueOf(d1.getName())
.compareTo(d2.getName());
}
return comparison;
}
});
}
public void selectionSort(ArrayList<Dog> dogs) {
int n = dogs.size();
// One by one move boundary of unsorted subarray
for (int i = 0; i < n - 1; i++) {
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i + 1; j < n; j++) {
Dog d1 = dogs.get(j);
Dog d2 = dogs.get(min_idx);
int comparison = Double
.valueOf(d1.getTailLength())
.compareTo(d2.getTailLength());
if (comparison == 0) {
comparison = String
.valueOf(d1.getName())
.compareTo(d2.getName());
}
if (comparison < 0)
min_idx = j;
}
// Swap the found minimum element with the first
// element
// using built in swap
// Collections.swap(dogs, min_idx, i);
// using classic temp method
Dog temp = dogs.get(min_idx);
dogs.set(min_idx, dogs.get(i));
dogs.set(i, temp);
// using classic method without temp element
// dogs.set(i, dogs.set(min_idx, dogs.get(i)));
}
}
}
Here is also a repl, where you can see this function in practice: https://repl.it/repls/VividMeekPlans

Getting Java methods from one object and a constructor from another object

I have three class Homework that has my main(...), GradeArray, which has my methods, and StudentGrade, which has my constructor.
Currently , which is clearly wrong, I have in Homework:
GradeArray grades = new GradeArray();`
In GradeArray at the top I have StudentGrade[] ArrayGrades = new StudentGrade[size]; however this method did not give me both the contructor and the methods. I know I don't need three classes for this but my professor wants three class. How do I declare an array that has attributes from two classes so that I can get the methods from GradeArray and the constructor from StudentGrade?
Thank you for you time and help.
Here is all of my code
package homework1;
public class Homework1
{
public static int pubSize;
public static String pubCourseID;
public static void makeVarsPub(int maxSize, String courseID) //this is to makes the varibles public
{
pubSize = maxSize;
pubCourseID = courseID;
}
public int giveSize()
{
return pubSize;
}
public static void main(String[] args)
{
int maxSize = 100;
String courseID = "CS116";
//this is to makes the varibles public
makeVarsPub(maxSize, courseID);
StudentGrade grades = new StudentGrade();
grades.insert("Evans", 78, courseID);
grades.insert("Smith", 77, courseID);
grades.insert("Yee", 83, courseID);
grades.insert("Adams", 63, courseID);
grades.insert("Hashimoto", 91, courseID);
grades.insert("Stimson", 89, courseID);
grades.insert("Velasquez", 72, courseID);
grades.insert("Lamarque", 74, courseID);
grades.insert("Vang", 52, courseID);
grades.insert("Creswell", 88, courseID);
// print grade summary: course ID, average, how many A, B, C, D and Fs
System.out.println(grades);
String searchKey = "Stimson"; // search for item
String found = grades.find(searchKey);
if (found != null) {
System.out.print("Found ");
System.out.print(found);
}
else
System.out.println("Can't find " + searchKey);
// Find average and standard deviation
System.out.println("Grade Average: " + grades.avg());
System.out.println("Standard dev; " + grades.std());
// Show student grades sorted by name and sorted by grade
grades.reportGrades(); // sorted by name
grades.reportGradesSorted(); // sorted by grade
System.out.println("Deleting Smith, Yee, and Creswell");
grades.delete("Smith"); // delete 3 items
grades.delete("Yee");
grades.delete("Creswell");
System.out.println(grades); // display the course summary again
}//end of Main
}//end of homework1
package homework1;
class GradeArray
{
int nElems = 0; //keeping track of the number of entires in the array.
Homework1 homework1InfoCall = new Homework1(); //this is so I can get the information I need.
int size = homework1InfoCall.giveSize();
StudentGrade[] ArrayGrades = new StudentGrade[size];
public String ToString(String name, int score, String courseID)
{
String res = "Name: " + name + "\n";
res += "Score: " + score + "\n";
res += "CourseID " + courseID + "\n";
return res;
}
public String getName(int num) //returns name based on array location.
{
return ArrayGrades[num].name;
}
public double getScore(int num) //returns score based on array location.
{
return ArrayGrades[num].score;
}
public void insert(String name, double score, String courseID) //part of the insert method is going to be
//taken from lab one and modified to fit the need.
{
if(nElems == size){
System.out.println("Array is full");
System.out.println("Please delete an Item before trying to add more");
System.out.println("");
}
else{
ArrayGrades[nElems].name = name;
ArrayGrades[nElems].score = score;
ArrayGrades[nElems].courseID = courseID;
nElems++; // increment the number of elements
};
}
public void delete(String name) //code partly taken from lab1
{
int j;
for(j=0; j<nElems; j++) // look for it
if( name == ArrayGrades[j].name)
break;
if(j>nElems) // can't find it
{
System.out.println("Item not found");
}
else // found it
{
for(int k=j; k<nElems; k++) // move higher ones down
{
boolean go = true;
if ((k+2)>size)
go = false;
if(go)
ArrayGrades[k] = ArrayGrades[k+1];
}
nElems--; // decrement size
System.out.println("success");
}
}
public String find (String name){ //code partly taken from lab1
int j;
for(j=0; j<nElems; j++) // for each element,
if(ArrayGrades[j].name == name) // found item?
break; // exit loop before end
if(j == nElems) // gone to end?
return null; // yes, can't find it
else
return ArrayGrades[j].toString();
}
public double avg() //this is to get the average
{
double total = 0;
for(int j=0; j<nElems; j++)
total += ArrayGrades[j].score;
total /= nElems;
return total;
}
public double std() //this is to get the standard deviation. Information on Standard deviation derived from
//https://stackoverflow.com/questions/18390548/how-to-calculate-standard-deviation-using-java
{
double mean = 0; //this is to hold the mean
double newSum = 0;
for(int j=0; j < ArrayGrades.length; j++) //this is to get the mean.
mean =+ ArrayGrades[j].score;
for(int i=0; i < ArrayGrades.length; i++) //this is to get the new sum.
newSum =+ (ArrayGrades[i].score - mean);
mean = newSum/ArrayGrades.length; //this is to get the final answer for the mean.
return mean;
}
public StudentGrade[] reportGrades() //this is grade sorted by name
{
int in,out;
char compair; //this is for compairsons.
StudentGrade temp; //this is to hold the orginal variable.
//for the first letter cycle
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(0);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(0) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
//this is for the second run.
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(1);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(1) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
return ArrayGrades;
}
public StudentGrade[] reportGradesSorted() //this is grades sorted by grades.
//this is grabbed from lab2 and repurposed.
{
int in,out;
double temp;
for(out=1; out<ArrayGrades.length; out++)
{
temp=ArrayGrades[out].score;
in=out;
while(in>0 && ArrayGrades[in-1].score>=temp)
{
ArrayGrades[in]= ArrayGrades[in-1];
in--;
}
ArrayGrades[in].score=temp;
}
return ArrayGrades;
} //end of GradeArray
package homework1;
public class StudentGrade extends GradeArray
{
public String name;
double score;
public String courseID;
public void StudentGrade (String name, double score, String courseID) //this is the constructor
{
this.name = name;
this.score = score;
this.courseID = courseID;
}
}//end of StudentGrade class.
First, I feel #Alexandr has the best answer. Talk with your professor.
Your question doesn't make it quite clear what you need. However, it sounds like basic understanding of inheritance and class construction would get you going on the right path. Each of the 3 classes will have a constructor that is unique to that type. Each of the 3 classes will have methods and data (members) unique to those types.
Below is just a quick example of what I threw together. I have strong concerns that my answer is actually what your professor is looking for however--it is not an object model I would suggest--just an example.
public class Homework {
private String student;
public Homework(String name) {
student = name;
}
public String getStudent() {
return student;
}
}
public class StudentGrade extends Homework {
private String grade;
public StudentGrade(String grade, String name) {
super(name);
this.grade = grade;
}
public String getGrade() {
return grade;
}
}
public class HomeworkGrades {
public List<StudentGrade> getGrades() {
// this method isnt implemented but should
// be finished to return array of grades
}
}
Take a look and see if that helps you understand something about inheritance and class construction.
Hopefully you can infer a bit about inheritence (StudentGrade inherits -- in java extends -- from HomeWork) and class construction.
Thnx
Matt
I change the array creation in Homework1 to be StudentGrade grades = new StudentGrade(); and I added extends GradeArray to the StudentGrade class. it is now public class StudentGrade extends GradeArray.

Java getTopStudent and getAverageScore using arrays

I've been studying code on my own, and I got a problem that I do not know how to answer.
I am given a student and classroom class, and from those two I need to be able to create a method for getTopStudent, as well as thegetAverageScore.
**Edit: All of the code was given except for the two methods, I needed to create those 2. The thing is that I'm not sure if what I'm doing is correct.
public class Student
{
private static final int NUM_EXAMS = 4;
private String firstName;
private String lastName;
private int gradeLevel;
private double gpa;
private int[] exams;
private int numExamsTaken;
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
exams = new int[NUM_EXAMS];
numExamsTaken = 0;
}
public double getAverageScore() //this is the method that I need to, but I'm not sure if it is even correct.
{
int z=0;
for(int i =0; i<exams.length; i++)
{
z+=exams[i];
}
return z/(double) numExamsTaken;
}
public String getName()
{
return firstName + " " + lastName;
}
public void addExamScore(int score)
{
exams[numExamsTaken] = score;
numExamsTaken++;
}
public void setGPA(double theGPA)
{
gpa = theGPA;
}
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
public class Classroom
{
Student[] students;
int numStudentsAdded;
public Classroom(int numStudents)
{
students = new Student[numStudents];
numStudentsAdded = 0;
}
public Student getTopStudent() //this is the other method I need to create
{
int x=0;
int y=0;
for(int i =0; i<numStudentsAdded; i++)
{
if(x<students.getAverageScore())
{
x=students.getAverage();
y++;
}
}
return students[y];
}
public void addStudent(Student s)
{
students[numStudentsAdded] = s;
numStudentsAdded++;
}
public void printStudents()
{
for(int i = 0; i < numStudentsAdded; i++)
{
System.out.println(students[i]);
}
}
}
I have something down for each of them but it isn't running. I don't fully understand arrays yet, but this is apparently a beginner code using arrays. If anyone could help with what I need to do and tell me how arrays work, much would be appreciated.
getAverageScore() is a method of Student. But students is not a Student object, it's an array of Student objects. (And getAverage(), which you call inside the for loop, isn't a method at all.) An array is a separate object that contains other objects or primitives (like ints) in it. So students.getAverageScore() is not going to compile, because students doesn't have that method, each of its members (student[0], student[1], etc.) has it.
Try replacing the getTopStudent method with something like this:
public Student getTopStudent() //this is the other method I need to create
{
int x=0; //this will contain the highest average
int y=0; //this will be the index in the array of the highest scoring student
for(int i =0; i<numStudentsAdded; i++)
{
int currentAverage = students[i].getAverageScore(); //run the getAverageScore() on the current student
if(x<currentAverage) // compare it to the previous high average
{
x=currentAverage; // replace x with new high average
y=i; //replace the index of the highest scoring student with current index i
}
}
return students[y]; // so if the fifth student had the highest score, y would be 4
}
So you are having trouble int the method public Student getTopStudent()
public Student getTopStudent() //this is the other method I need to create
{
double x= students[0].getAverageScore();
int y = 0;
for(int i=1;i<students.length;i++){
if(x<students[i].getAverageScore()) {
x = students[i].getAverageScore();
y =i;
}
}
return students[y];
}
See if this helps

JAVA Data Overwrite error

I have an assignment to write a program to project your annual fuel usage based on three fill ups of a car. I have to use two separate classes. This is my first class, titled AnnualFuelUse.
public class AnnualFuelUse
{
private static int endMiles, startMiles,fillUp, days,distance;
private double gallonsUsed, pricePerGallon,MPG,cost;
AnnualFuelUse(int fu, int d, int sm, int em, double gu, double price)
{
fillUp = 0;
days = d;
startMiles = sm;
endMiles = em;
gallonsUsed = gu;
pricePerGallon = price;
distance = 0;
MPG = 0.0;
cost = 0.0;
}
public void calcDistance ()
{
distance = endMiles - startMiles;
}
public int getDistance(){
return distance;
}
//calculates miles per gallon
public void calcMPG()
{
MPG = distance /gallonsUsed;
}
public double returnMPG(){
return MPG;
}
public void totalCost(){
cost= gallonsUsed * pricePerGallon;
}
public double getCost(){
return cost;
}
public int returnStart(){
return startMiles;
}
public int returnEnd(){
return endMiles;
}
public int returnDays(){
return days;
}
public double returnGallons(){
return gallonsUsed;
}
public double returnPrice(){
return pricePerGallon;
}
}
This is my second class, titled AnnualFuelUseTester. (sorry for the long names, but it's required)
public class AnnualFuelUseTester
{
public static void main(String[]args)
{
AnnualFuelUse[]fuel = {new AnnualFuelUse(1,1,45023,45231,10.00,2.95),
new AnnualFuelUse(2,4,45231,45480,11.70,2.99),
new AnnualFuelUse(3,8,45480,45659,9.30,3.01),
new AnnualFuelUse(4,13,45659,45961,14.90,3.01)};
for (int index = 0; index<fuel.length;index++)
{
fuel[index].calcDistance();
fuel[index].calcMPG();
fuel[index].totalCost();
}
System.out.println(" Fill Up Days Start Miles End Miles Distance Gallons Used MPG Price Cost ");;
for(int index = 0; index < fuel.length; index++)
{
System.out.printf("%5d %6d %9d %12d %12d %10.2f %13.1f %6.2f %6.2f \n",
index+1,fuel[index].returnDays(),fuel[index].returnStart(),fuel[index].returnEnd(),fuel[index].getDistance(),fuel[index].returnGallons(),fuel[index].returnMPG(),fuel[index].returnPrice(),fuel[index].getCost());
}
My problem is that when I run the program, the days, start miles, end miles, and distance columns all have the same numbers in them, the data for the last fill up. The gallons used, MPG, Price, Cost, all work fine. So in the Days Column, instead of reading 1, 4, 8, 13, it reads 13, 13, 13, 13.
I would appreciate some help in fixing this problem.
Your fields should not be static. That means one per class (not instance)
private static int endMiles, startMiles,fillUp, days,distance;
should be
private int endMiles, startMiles,fillUp, days,distance;

Possible fix for getting NaN in java

I have a method in the Candy Class named pricePerHundredGrams and what it is supposed to do is multiply the variable price times 100.00 and divide that answer by the variable weightGrams, and finally return that result to the variable wammy. When the variable wammy is called for in the very 2nd last statement of this code, it is supposed to pass the answer to return result. And ultimately c1 and c2 should display that result as well...but I get NaN for "per hundred grams". What is wrong with my code?
public class whatever
{ public static void main (String[] args)
{
processCandies();
System.out.println("end of processing");
}
public static void processCandies()
{
Candy c1 = new Candy("Hershey", 145, 4.35, 233);
Candy c2 = new Candy("Milky Way", 390, 2.66, 126);
System.out.println(c1);
System.out.println(c2);
}
}
class Candy
{
private String name;
private int calories;
private double price;
private double weightGrams;
double wammy = pricePerHundredGrams(price, weightGrams);
/**
Constructor
#param name
#param calories
#param price
#param gram
*/
public Candy(String n, int cal, double p, double wG)
{
name = n;
calories = cal;
price = p;
weightGrams = wG;
}
public String getName()
{
return name;
}
public int getCalories()
{
return calories;
}
public double getPrice()
{
return price;
}
public double getWeightGrams()
{
return weightGrams;
}
public double pricePerHundredGrams(double price, double weightGrams)
{
return (price * 100.00) / weightGrams;
}
public String toString()
{
String result;
result = name + "\n" + calories + " calories\n" + weightGrams + " grams\n" + wammy + " per hundred grams\n";
return result;
}
}
You are initializing wammy with the result of pricePerHundredGrams, but price and weightGrams haven't been initialized yet, so they're both 0. For double arithmetic, 0 divided by 0 is NaN (it's indeterminate in math).
Initialize wammy after price and weightGrams have valid values in your constructor:
public Candy(String n, int cal, double p, double wG)
{
name = n;
calories = cal;
price = p;
weightGrams = wG;
// Initialize wammy here.
wammy = pricePerHundredGrams(price, weightGrams);
}
Additionally, since they are already instance variables, you don't need to pass price and weightGrams as parameters to pricePerHundredGrams.

Categories