【问题标题】:How can I access value of ID to find the average? [closed]如何访问 ID 的值以找到平均值? [关闭]
【发布时间】:2020-10-16 01:45:44
【问题描述】:

我有静态方法 Das,它将获取 2 个 Car 类型的对象并返回 id 的平均值。我很难访问 id 来找到平均值。任何帮助将不胜感激

这是我的代码

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);
}}

【问题讨论】:

  • 错误是什么?
  • 我无法在方法中访问id
  • 那是因为它们是私有的
  • 公开他们
  • 创建一个属性来访问它们?

标签: java static-methods


【解决方案1】:

对于int 退货,您将丢失分数,请按以下步骤操作。

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

对于double 不会丢失分数的返回

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

【讨论】:

  • 不确定是什么意思。静态方法可以访问私有值,因为它们在声明它们的类中被引用。
  • OP 将方法声明为静态的。我没有解释或演示如何调用它。这也不是问题。
  • OP 想知道如何计算平均值。请注意此处需要帮助的评论。这就是我所关注的。并且没有冒犯任何事情。
猜你喜欢
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多