Missing Return Statement?

后端 未结 6 1165
半阙折子戏
半阙折子戏 2021-01-25 20:52

This is my code. when I compile using bluej it highlights the last } and says missing return statement. I cant put void because it is a boolean. ANy ideas?

 p         


        
6条回答
  •  不知归路
    2021-01-25 21:29

    You have specified a boolean return type but your function doesn't return any value.

    The jobsFinished variable is redundant, as is your else branch:

    public boolean runAJob() {
        Job firstJob = getCurrentJob();    
        int jobDuration = firstJob.getDuration();
    
        if (!myJob.isEmpty() && jobDuration > 0 && jobDuration <= myTotalDuration) { 
            String jobName = firstJob.getName();
            myTotalDuration -= jobDuration;
            myFinishedJobs.add(myJob.get(0));
            myJob.remove(0);
            System.out.println("'"+jobName+"'" +" is completed. "+ myTotalDuration+ " seconds remaining on the clock");
            return true;
        } 
    
        System.out.println("JobQueue is empty");
        return false;
    }
    

    If the conditions are satisfied, the function will return before the last two statements anyway, so an else isn't necessary. I also moved the String jobName = firstJob.getName(); inside the if branch because you're not using it otherwise.

    If you prefer to use a boolean variable, and return it at the end of the function, then you could do:

    public boolean runAJob() {
        Job firstJob = getCurrentJob();    
        int jobDuration = firstJob.getDuration();
        boolean jobsFinished = !myJob.isEmpty() && jobDuration > 0 && jobDuration <= myTotalDuration;
        if (jobsFinished) { 
            String jobName = firstJob.getName();
            myTotalDuration -= jobDuration;
            myFinishedJobs.add(myJob.get(0));
            myJob.remove(0);
            System.out.println("'"+jobName+"'" +" is completed. "+ myTotalDuration+ " seconds remaining on the clock");            
        } 
        else {
            System.out.println("JobQueue is empty");
        }   
        return jobsFinished;
    }
    

提交回复
热议问题