【问题标题】:Am I oversimplifying returns?我是否过度简化了回报?
【发布时间】: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 - 不幸的是,这对某些人来说并不容易 :)
  • 这种情况下没问题。学习愉快!!

标签: java arrays return


【解决方案1】:

您需要添加一行来为 else 部分返回一个 int。当您在函数中有non-void 返回类型时,您需要显式地为所有代码分支(if-else)返回一个值。

public int questionsMissed() 

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

在这里为前return -1返回一个int

}

【讨论】:

    【解决方案2】:

    如果您的方法已声明返回int,它必须在任何情况下返回int,如果您想循环所有项目并检查数组是否包含'0'。如果全部失败return -1或@ 987654324@

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

    注意:变量名应以小写开头。回答而不是回答

    【讨论】:

    • 非常感谢 - 这非常有效,终于让我的班级编译了一个星期天!但是由于某种原因,当我运行我的演示程序时,我收到了这个错误:不兼容的类型 int 不能转换为 int[]。我的程序中与此相关的代码行是:
    • // 获取遗漏问题编号的数组。错过的问题=考试.questionsMissed();
    • if (missedQuestions != null) { System.out.println("你错过了以下问题:"); for (int i = 0; i
    • 这只是同样的问题吗?很抱歉给您添麻烦了,但最后几位似乎让我很难过!
    【解决方案3】:

    警告是因为在 questionsMissedqMissed 两个函数中,返回类型都应该是 int。在检查if 条件后,您将在循环内返回,这是绝对正确的,但是当if 语句永远不会计算为真时会发生什么,您的函数将永远不会返回任何内容,这就是警告的原因。为避免这种情况,您应该在for 循环之后添加一个返回语句。

    【讨论】:

      【解决方案4】:

      几个建议:

      1) 您将正确答案保存在数组中的方法很好。将实际答案传递给构造函数的想法也是如此。好!

      2) 每次您想知道#/正确答案或#/不正确答案时,与其遍历两个数组,不如只遍历数组ONCE,然后保存供您将来参考所需的一切。在你的情况下,我在构造函数中做了这个。

      3) 迟早你会遇到"Java Beans""getter and setter" 方法。严格来说,您的“DriverExam”不是 Java Bean(它没有零参数构造函数),但标准的“getter”命名约定很有用。我已将您的字段标记为“私有”并将您的访问方法更改为“getter”命名约定:getTotalCorrect() 等。

      4) 我还添加了一个检查,如果学生碰巧回答的问题少于整个测试。

      这里是修改后的代码:

      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);
              }
      
          }
      }
      

      这是示例输出:

      #/correct=18, #/missed=2, passed=true
      Questions missed: 
        1
        2
      

      【讨论】:

        【解决方案5】:

        我认为返回 index++ 或 index + 1 应该没问题,但似乎并非所有代码路径都返回 int。例如,在 questionsMissed() 中,您有一个 if 语句来检查 0 并在这种情况下返回一个 int,但如果检查返回 false,则不会返回任何 int。你可以把它改成这样:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-10-29
          • 2017-07-26
          • 1970-01-01
          • 1970-01-01
          • 2012-02-11
          • 2020-05-08
          • 2010-10-23
          • 2012-04-10
          相关资源
          最近更新 更多