Am I making it easy to return?
Basically, I am doing an old driver exam program for the uni course and I have designed the whole class. When I try to compile it, when running at the command line, I get the error:
missing return statement
and in Eclipse:
This method should return a result of type int` related to my methods that skipped the questions.
Now I think I already knew what the problem was before I tried to compile - my method is a type int
, and since my answers are "array is char" when I try to return "index + 1" or 'index ++), returning actual item, character (i.e. answer a, b, c, d). What I wanted to do was return the subscript number + 1 (to remove one error), so when I write the program, I can systematically print "you missed question 1, 3, 5, etc.".
I realize that there are probably a million other bugs in this code, but for now I just hope someone can help me with this. Understand this, perhaps simple and silly, but spend hours reading the forums and my tutorials and you can't figure it out. Perhaps I'm trying to simplify too simply by just using index + 1 to show the number of the missing number.
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;
}
}
source to share
If your method declared return int
, it must return int
for any case, if you want to loop through all elements and check if the array contains "0" or not. If everything fails return -1
orthrow 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 must start the variable name with lowercase. answer and not answer
source to share
You need to add a line to return an int for the else part. When you have a return type non-void
in a function, you need to explicitly return a value for all branches of the code (if-else).
public int questionsMissed()
{
for (int index = 0; index < 20; index++)
{
if (Answers[index] == 0)
return index + 1;
}
returns int here for ex
return -1
}
source to share
The warning is caused by the fact that in both functions questionsMissed
and qMissed
return types must be int. What do you return inside the loop after checking the condition if
, which is absolutely correct, but what happens when the operator if
never evaluates to true, your function will never return anything, hence the warnings. To avoid this, you must add a return statement after the loop for
.
source to share
A few suggestions:
1) Your approach to storing correct answers in an array is good. So is the idea of passing actual responses to the constructor. Good!
2) Instead of iterating through both arrays every time you want to know the correct answers # /, or # / wrong answers, it might be more efficient to loop through the array just once and store whatever you need for future reference. In your case, I did it in the constructor.
3) Sooner or later you will come across "Java Beans" and "getter and setter" . Strictly speaking, your "DriverExam" is not a Java Bean (it has no null-argument constructor), but the standard "getter" naming convention is useful. I've marked your fields "private" and changed your accessors to the naming convention "getter": getTotalCorrect()
etc.
4) I also added a check if the student answered fewer questions than the entire test.
Here's 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's an example of the output:
#/correct=18, #/missed=2, passed=true
Questions missed:
1
2
source to share
I think the returned c ++ or index + 1 should be exact, but it seems that not all code paths return int. For example, in the Missed () questions, you have an if statement to test for 0 and return an int in that case, but if the test returns false, no int is returned. You can change it to the following:
public int questionsMissed()
{
for (int index = 0; index < 20; index++)
{
if (Answers[index] == 0)
{
return index + 1;
}
}
return 0;
}
source to share