【问题标题】:Using a method with a custom type Feature parameter使用带有自定义类型 Feature 参数的方法
【发布时间】:2020-11-01 23:20:57
【问题描述】:

所以我有三个课程,因为我正在尝试练习如何使用自定义类型对象并且遇到了问题。在我的 Auto 类中,我创建了一个名为 showFeature() 的方法,我希望该方法接受一个参数,该参数将是自定义类型 Feature,它会打印出功能的名称和成本(例如:功能裤成本:3000.0 )。但是当我做这个方法时,它一直在 Feature 的最后一个引用中说期待。谁能帮我解决这个问题

public class Feature
{
    public String name;
    public double cost;
    public Feature(String s, double d){
        //step 1
        name = s;
        cost = d;
    }
    //step 4
}


public class TestAuto
{
   public static void main(String args[]){
    //instantiate an Auto object
    Auto at = new Auto("AMG", 73.5);

    //instantiate a Feature object
    Feature fe = new Feature("Leather Seat", 3000);

    //execute method addFeature with Feature object
    at.showFeature(fe);

    //prepare a new Feature object for receving information
    Feature fe1 = new Feature("", 0);

    //Run method discountValue with a feature and a new value
    fe1 = at.discountValue("GPS", 15000, 0.2);

    //print out the object
    System.out.println(fe1);
   }
}



public class Auto
{
    public String name;
    public double size;
    public Auto(String s, double sz){
        name = s;
        size = sz;
    }
    //step 2: method showFeature()
    public Feature showFeature(Feature){
        
        System.out.println("The feature " +s+" costs: "+d);
        
    }
    public Feature discountValue(String s, double c, double d){
    //Step 3: method to give discount on cost
        double f = c - d;
        return f;
    }
}




【问题讨论】:

  • 您的代码无法编译。请提供至少处于工作状态的东西。

标签: java parameters custom-object


【解决方案1】:

现在你让它接受一个没有附加变量的功能。您有一个要素类,它创建了一个接受 String 和 Double 的要素对象,这可能就是为什么会有预期的注释,因为您没有为该要素提供任何输入。

//step 2: method showFeature()
public Feature showFeature(Feature f){
    
    System.out.println("The feature " + f +" costs: "+ f.cost);
    
}

【讨论】:

    猜你喜欢
    • 2012-09-29
    • 2020-08-24
    • 2021-02-14
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多