猿问

java中的setter和getter

我有两个文件,一个是驱动程序,我在使用 setter 时遇到问题。看起来确实设置了值。


public class Movie {

private String name;

private int minutes;

protected int tomatoScore;


public Movie(String name, int minutes, int tomatoScore)

{

    this.name=name;

    this.minutes=minutes;

    this.tomatoScore=tomatoScore;

}


public String getName() {return name;}

public void setName(String name) {this.name=name;}

public int getMinutes() {return minutes;}

public boolean setMinutes(int minutes) {return minutes>=0;}

public int getTomatoScore() {return tomatoScore;};

public boolean setTomatoScore(int tomatoScore) {return tomatoScore>=0 &&tomatoScore<=100;};

public boolean isFresh() {return tomatoScore>=60;};


public void display()

{

    //this.name = name;

    //this.minutes = minutes;

    //this.tomatoScore =tomatoScore;


    System.out.println("Movie: "+ getName());

    System.out.println("Length: "+ getMinutes() +"min.");


    if(tomatoScore>=60)

    {

        System.out.println("TomatoScore: Fresh");

    }

    else 

    {

        System.out.println("TomatoScore: Rotten");

    }



}

}


下面是驱动程序文件,如果您注意到设置器确实完成了应该做的工作我相信问题是电影类,如果您运行驱动程序来测试程序,您会看到是否将值设置为负值 if 语句无法正常运行。( setMinutes 和 setTomatoScore 是错误的。它们根本没有设置类字段)


慕后森
浏览 144回答 3
3回答

弑天下

您的setMinutes和setTomatoScore方法不设置任何内容,它们只返回一个布尔值。我假设您忘记添加this.tomatoScore = tomatoScore例如。

德玛西亚99

您需要tomatoScore在方法状态中设置一些内容,如下所示:public boolean setTomatoScore(int tomatoScore) {&nbsp; if (tomatoScore >= 0 && tomatoScore <= 100) {&nbsp; &nbsp; this.tomatoScore = tomatoScore;&nbsp; &nbsp; return true;&nbsp; }&nbsp; return false;}

慕桂英3389331

看起来你需要这个:&nbsp; &nbsp; &nbsp; &nbsp;public boolean setMinutes(int minutes) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(minutes >= 0 && minutes < 60) {&nbsp;&nbsp; &nbsp; //I'm guessing the <60 part here, but whatever,&nbsp;&nbsp; &nbsp; //this is how you'd set the 100 limit on your setTomatoScore method&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.minutes = minutes;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }做类似的修正 setTomatoScore
随时随地看视频慕课网APP

相关分类

Java
我要回答