Search code examples
javastatic-methods

How can I access value of ID to find the average?


I have static method Das which will take 2 objects of type Car and return average value of id. I have difficulty accessing id to find the average. Any help will be appreciated

Here is my code

public class Car {

private int id;
private String name;

public Car(int id, String name)
{
this.id = id;
this.name = name;
}

public static int Das( Car C1 , Car C2) {
{
return (C1.id + C2.id)/2 ;
}

// getter and setter

Test.java

public class Test {

public static void main(String[] args) {

Car car1 = new Car(1,"A");
Car car2 = new Car(2,"V");
double A= Das(car1,car2);
System.out.println(A);
}}

Solution

  • For an int return where you will lose fractions, do it as follows.

    public static int findAveCustomerId(Customer C1 , Customer C2) {
       return (C1.id + C2.id)/2;
    }
    

    For a double return where you won't lose fractions

    public static double findAveCustomerId(Customer C1 , Customer C2) {
       return (C1.id + C2.id)/2.; // notice the decimal point.
    }