如果OOP为空,如何设置位置

问题描述 投票:0回答:1

如果最初未输入位置,我该如何打印“整个房子”字样。我认为它不起作用,因为创建任务时,它使用的是没有位置说明的构造函数。有没有办法将位置从null更改为我指定的字符串?

这是我的Task类:

public class Task{

    private final String choreName; 
    private final int maxCompletionInMinutes;
    private final String difficulty;
    private String location;

    public Task(String choreName, int maxCompletionInMinutes, String difficulty){
       this.choreName = choreName;
       this.maxCompletionInMinutes = maxCompletionInMinutes;
       this.difficulty = difficulty;
    }

    public Task(String choreName, int maxCompletionInMinutes, String difficulty, String location){
       this(choreName, maxCompletionInMinutes, difficulty);
       this.location = location;
    }

    public String getChoreName(){
        return choreName; 
    }    
    public int getMaxCompletionInMinutes(){
        return maxCompletionInMinutes;
    }
    public String getDifficulty(){
        return difficulty;
    }
    public String getLocation(){
        return location;
    }

    public void setLocation(String location){
        if(location == null)
        location = "Whole house";

        this.location = location;
    }

    public void prettyPrint(){
        System.out.printf("Complete the chore: %s (%s) in location: %s. This chore should take a maximum of %d minutes.%n", choreName, difficulty, location, maxCompletionInMinutes);
    }

}

这是我的驱动程序类:

public class Assignment5{
    public static void main (String[] args){
        Task task1 = new Task("Dishes", 40, "Hard", "Kitchen");
        Task task2 = new Task("Dust", 45, "Hard");
        Task task3 = new Task("Vacuum", 30, "Medium");
        Task task4 = new Task("Make beds", 15, "Easy");
        Task task5 = new Task("Water plants", 15, "Easy", "Living Room");

        task1.prettyPrint();
        task2.prettyPrint();
        task3.prettyPrint();
        task4.prettyPrint();
        task5.prettyPrint();
    }

}
java oop getter-setter
1个回答
1
投票

我可能只是切换构造函数的顺序。使三个参数构造函数调用四个参数构造函数并提供默认值:

public Task(String choreName, int maxCompletionInMinutes, String difficulty) {
   this(choreName, maxCompletionInMinutes, difficulty, "Whole house");
}

public Task(String choreName, int maxCompletionInMinutes, String difficulty, String location) {
   this.choreName = choreName;
   this.maxCompletionInMinutes = maxCompletionInMinutes;
   this.difficulty = difficulty;
   this.location = location;
}

然后仅删除设置器中的空检查逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.