2016-11-18 203 views
1

我是一個初學者到Java,我奉命執行以下操作:如何將變量指定爲參數?

  • 創建一個新類Food
  • 被指定爲參數的食物的名稱。
  • 食物名稱的吸氣方法。

我的嘗試是這樣的:

public class Food 
{ 
    String food;  

    Food() { 
     food = ""; 
    } 
    public String getFood() { 
     return food; 
    } 
} 

我會食品名稱被指定爲參數更改爲:

Food(String food) { 
    food = ""; 
} 

或者任何不同的方式?謝謝。

回答

0

是的,你必須給個說法分配給您存儲食物的名稱的字段。這是評論中的解釋代碼。

//class Food 
public class Food { 

    //field that stores the name of the food 
    private String name; 

    //constructor that takes the name of the food as an argument 
    public Food(String name){ 
     this.name = name; 
    } 

    //getter 
    public String getName() { 
     return name; 
    } 
} 
1

是,那麼請確保使用參數在體內:

Food(String food) { 
    // need `this` to refer to instance variable food since there's 
    // scope overlap. 
    this.food = food; 
} 
-1
public class Food { 


    String food;  

    Food() 
    { 

    } 

     public String getFood() 
    { 

     return food; 

    } 



    public void setFood(String food) 


    { 

     //this is used as to set the value that you passed from your main class  throught your object 

      this.food = food; 
     } 

     /** 
     * @param args the command line arguments 
     */ 
     public static void main(String[] args) { 

      Food object=new Food(); 
      object.setFood("Apple"); 
      String name= object.getFood(); 

      System.out.print(name); 

     } 

    } 
相關問題