3

Basically I'm doing the old driver exam program for a uni course and I've drafted out the whole class. When I try to compile it, if working in command prompt, I get the error:

missing return statement

and in Eclipse:

This method must return a result of type int` pertaining to my methods re missed questions.

Now I think I already knew what the problem was before trying to compile - my method is an int type, and because my answers "array is char", when I try to return 'index + 1' or 'index++) it's returning the actual element, a character (i.e. answer a,b,c, d). What I wanted to do was to return the subscript number + 1 (to remove out by one error), so when I write the program, I can system out print 'you missed question 1, 3, 5 etc'.

I realize there are probably a million other errors in this code, but right now I'm just hoping someone can help me with this one. Realize it's probably simple and stupid but have been reading forums and my textbooks for hours and can't figure this out. Maybe I'm trying to simplify too much by just using the subscript + 1 as a means of showing question number missed.

public class DriverExam {

private char[] rightAnswers = { 'b', 'd', 'a', 'a', 'c', 'a', 'b', 'a',   
'c', 'd', 'b', 'c', 'd', 'a', 'd', 'c', 'c', 'b', 'd', 'a' }; //Answers 
to test.
char[] Answers; //Student answer input.
int[] missed = {}; //Array for missed questions.
int correct = 0; //Create and initialise to 0.
int qMissed = 0; //Create and initialise to 0.

/** 
Constructor that accepts array of answers and copies to the answers array 
field.
@parem ans The array of student driver answers */


public DriverExam(char[] ans)
{
Answers = ans;
}

/**
An int array containing the question numbers of those questions that the 
student missed.
*/

public int questionsMissed() 

{
for (int index = 0; index < 20; index++) //Ask program to step through 
each element in array Answers.
    {
    if (Answers[index] == 0) //I'm assuming here that a question not 
    answered = 0, not null as it would for string.
        return index + 1; //I want to return the subscript assigned to 
    any questions that = 0 ie haven't been answered, plus 1 to avoid out 
    by one error.
    }
    }

public int qMissed() 
{
for (int index = 0; index < 20; index++) //Ask program to step through    
each element in array Answers.
    {
    if (Answers[index] == 0) //Asking it to repeat process above.
        return index++; //I want to ask it to take the subscript and add 
1 to the existing subscript for all additional missed questions.
        }
}


/**
A method that returns the total number of correctly answered questions.
@return Returns the number of correctly answered questions.
*/

public int totalCorrect()
{
for (int index = 0; index < Answers.length; index++)
{
if (Answers[index] == rightAnswers[index]) 
correct++;
}
return correct;
}


/**
A method that returns the total number of incorrectly answered questions.
@return Returns the number of incorrect answers.
*/

public int totalIncorrect()
{
    int incorrect = (rightAnswers.length - (totalCorrect() + qMissed));
    return incorrect;
}

/**
A method that returns true if the student passed the exam, or false if    
the student failed.
*/


public boolean passed()
{
    if(totalCorrect() >= 10); return true;
}

}
Jamal
  • 763
  • 7
  • 22
  • 32
Newbie
  • 53
  • 1
  • 5
  • You are simply missing a return statement as the message clearly states. IMO, you should be able to find such small errors yourself rather than asking such questions at SO. – akhil_mittal May 03 '15 at 04:06
  • Sorry to bother akhil - this is only a few weeks into my course and I've never seen java previously - unfortunately it doesn't come easy to some :) – Newbie May 03 '15 at 07:42
  • In that case it is fine. Happy learning!! – akhil_mittal May 03 '15 at 11:58

5 Answers5

2

You need to add a line to return an int for the else part. When you have a non-void return type in a function, you need to explicitly return a value for all code branches (if-else).

public int questionsMissed() 

{
for (int index = 0; index < 20; index++) 
    {
    if (Answers[index] == 0) 
        return index + 1; 
    }

return a int here for ex return -1

}

Biswajit_86
  • 3,661
  • 2
  • 22
  • 36
0

If your method has declared to return int it must return int for any case,if you want to loop for all items and check whether array contains '0' or not.If all fails return -1 or throw Exception

public int questionsMissed() {
    for (int index = 0; index < 20; index++) {
        if (Answers[index] == 0) {
            return index + 1;
        }
    }
  return -1;//If nothing works
}

Note: You should start name of variable with lower case. answer and not Answer

akash
  • 22,664
  • 11
  • 59
  • 87
  • Thanks so much - this worked perfectly and FINALLY allowed my class to compile what a Sunday! For some reason now though, when I run my demo program, I'm getting this error: incompatible types int cannot be converted to int[]. The lines of code that pertain to this in my program are: – Newbie May 03 '15 at 07:39
  • // Get an array of the missed question numbers. missedQuestions = exam.questionsMissed(); – Newbie May 03 '15 at 07:40
  • if (missedQuestions != null) { System.out.println("You missed the following questions:"); for (int i = 0; i < missedQuestions.length; i++) System.out.print(missedQuestions[i] + " "); – Newbie May 03 '15 at 07:40
  • Is this just the same problem? Sorry to be a hassle but these last few bits just seem to have me stumped! – Newbie May 03 '15 at 07:41
0

The warning is because in both functions questionsMissed and qMissed the return types should be int. Which you are returning inside the loop after checking the if condition, which is absolutely correct, but what happens when the if statement never evaluates to true, your function will never return anything, that is why the warnings. To avoid this you should add a return statement after for loop.

Vikash Kesarwani
  • 850
  • 5
  • 14
0

A couple of suggestions:

1) Your approach of saving the correct answers in an array is a good one. So is the idea of passing the actual answers to the constructor. Good!

2) Instead of iterating through both arrays every time you want to know the #/correct answers, or #/incorrect answers - it's probably more efficient to loop through the array just ONCE, and save everything you need for future reference. In your case, I did this in the constructor.

3) Sooner or later, you'll encounter "Java Beans", and "getter and setter" methods. Stringly speaking, your "DriverExam" isn't a Java Bean (it doesn't have a zero-argument constructor), but the standard "getter" naming convention is useful. I've marked your fields "private" and changed your access methods to the "getter" naming convention: getTotalCorrect(), etc.

4) I also added a check if the student happened to answer fewer questions than the whole test.

Here is the modified code:

public class DriverExam {

    //Answers to test
    private char[] rightAnswers = { 
        'b', 'd', 'a', 'a', 'c', 'a', 'b', 'a',   
        'c', 'd', 'b', 'c', 'd', 'a', 'd', 'c', 'c', 'b', 'd', 'a' 
    }; 

    private boolean[] results;
    private int totalCorrect = 0; //Create and initialise to 0.
    private int totalMissed = 0; //Create and initialise to 0.

    /** 
    Constructor that accepts array of answers, grades the text, and computes #/correct and #/missed
    */
    public DriverExam(char[] ans)   {
        // Allocate array to hold results
        results = new boolean[rightAnswers.length];

        // Grade the test
        for (int i=0; i < rightAnswers.length; i++) {
            // ... Q: Did student complete this part of the test?
            if (i > ans.length-1) {
                results[i] = false;  //  Mark "incorrect"
                totalMissed++;
            }
            else if (ans[i] != rightAnswers[i]) {
                results[i] = false; // Mark "incorrect"
                totalMissed++;
            }
            else {
                results[i] = true;  // Mark "correct"
                totalCorrect++;

            }
        }
    }

    /**
    An boolean array containing which questions were answered correctly, and which weren't
    */
    public boolean[] getResults() {
        return results;
    }

    /**
    A method that returns the total number of correctly answered questions.
    */
    public int getTotalCorrect()    {
        return totalCorrect;
    }

    /**
    A method that returns the total number of questions missed.
    */
    public int getTotalMissed() {
        return totalMissed;
    }

    /**
    A method that returns true if the student passed the exam, or false if    
    the student failed.
    */
    public boolean isPassed()   {
        return (totalCorrect >= 10);
    }


    /**
     * Test driver
     */
    public static void main (String[] args) {
        char[] myAnswers = {
            'b', 'x', 'x', 'a', 'c', 'a', 'b', 'a',   
            'c', 'd', 'b', 'c', 'd', 'a', 'd', 'c', 'c', 'b', 'd', 'a' 
        }; 

        DriverExam myExam = new DriverExam (myAnswers);
        System.out.println ("#/correct=" + myExam.getTotalCorrect() + ", #/missed=" + myExam.getTotalMissed() + ", passed=" + myExam.isPassed());
        System.out.println("Questions missed: ");
        boolean[] myResults = myExam.getResults();
        for (int i=0; i < myResults.length; i++) {
            if (myResults[i] == false)
                System.out.println ("  " + i);
        }

    }
}

And here is sample output:

#/correct=18, #/missed=2, passed=true
Questions missed: 
  1
  2
Community
  • 1
  • 1
FoggyDay
  • 11,962
  • 4
  • 34
  • 48
-1

I think that returning index++ or index + 1 should be fine, but it appears that not all of your code paths are returning an int. For instance, in questionsMissed() you have an if statement to check for 0 and return an int in that case, but if the check returns false no int is getting returned. You might change it to something like this:

public int questionsMissed() 
{
    for (int index = 0; index < 20; index++)
    {
        if (Answers[index] == 0)
        {
            return index + 1;
        }
    }
    return 0;
}
John Hodge
  • 1,645
  • 1
  • 13
  • 13