【发布时间】:2015-07-12 15:43:51
【问题描述】:
基本上,我正在为一门大学课程做旧的驾驶员考试计划,并且我已经起草了整个班级。当我尝试编译它时,如果在命令提示符下工作,我会收到错误:
缺少返回语句
在 Eclipse 中:
此方法必须返回与我的方法有关的 int` 类型的结果,因为我错过了问题。
现在我想我在尝试编译之前就已经知道问题所在了 - 我的方法是 int 类型,并且因为我的答案是“array is char”,所以当我尝试返回 'index + 1' 或 'index++ ) 它返回实际元素,一个字符(即答案 a、b、c、d)。我想要做的是返回下标数字+1(以一个错误删除),所以当我编写程序时,我可以系统输出打印'你错过了问题1、3、5等'。
我意识到这段代码中可能还有一百万个错误,但现在我只是希望有人能帮助我解决这个问题。意识到这可能既简单又愚蠢,但是已经阅读论坛和我的教科书几个小时了,却无法弄清楚。也许我只是通过使用下标 + 1 作为显示遗漏问题编号的一种方式来简化太多。
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;
}
}
【问题讨论】:
-
您只是缺少一条返回声明,正如消息中明确指出的那样。 IMO,您应该能够自己发现这样的小错误,而不是在 SO 上问这样的问题。
-
抱歉打扰了 akhil - 我的课程才刚开始几周,我以前从未见过 java - 不幸的是,这对某些人来说并不容易 :)
-
这种情况下没问题。学习愉快!!