简体   繁体   中英

Restrict user input to certain value by using enum

public class Movie {
    private String title, director;
    private float overallRating;

    private enum showingStatus {ComingSoon, Preview, NowShowing};

    public Movie(String title, enum showingStatus, String director)
    {
        this.title = title;
        this.showingStatus = showingStatus;
        this.director = director;
        overallRating = 0;
    }
}

How do I restrict in such a way when someone creates Movie object, they pass in only my defined list of showingStatus ?

I also want to define the get and set methods but they are throwing errors pointed out on comments

public void setShowingStatus(enum showingStatus){ this.showingStatus = showingStatus;} // showingStatus cannot be resolved or not a field
public String getShowingStatus() { return showingStatus; } // showingStatus cannot be resolved to a variable

I think this might be what you're looking for.

public class Movie {
    private String title, director;
    private float overallRating;
    private ShowingStatus showingStatus;

    public enum ShowingStatus {ComingSoon, Preview, NowShowing}

    public Movie(String title, ShowingStatus showingStatus, String director)
    {
        this.title = title;
        this.showingStatus = showingStatus;
        this.director = director;
        overallRating = 0;
    }
}

Edit:

This is the same thing. You can't declare a enum type when passing in variable. It's whatever you made it to be. In this case, I set it as ShowingStatus , so you would say:

public void setShowingStatus(ShowingStatus showingStatus){ this.showingStatus = showingStatus;} // showingStatus cannot be resolved or not a field
public ShowingStatus getShowingStatus() { return showingStatus; } // showingStatus cannot be resolved to a variable

To allow ShowingStatus enums to get used by other classes, create a separate enum file by doing the following:

public enum ShowingStatus {
    ComingSoon, Preview, NowShowing
}

And now, other classes should be able to call ShowingStatus.ComingSoon or any other enum elements within ShowingStatus.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM