简体   繁体   English

正确调用方法:(Java)

[英]Calling a method correctly: (Java)

Create a method named getNextProjectIndex() that returns an int that gets the next index of the projects array that contains a -1.0. 创建一个名为getNextProjectIndex()的方法,该方法返回一个整数,该整数获取包含-1.0的项目数组的下一个索引。 Find the next item in the projects array that contains a -1.0 and return that index of the array. 在包含-1.0的项目数组中找到下一个项目,然后返回该数组的索引。 This method should return -1 if the array is full. 如果数组已满,则此方法应返回-1。 -1 is a common flag to indicate failure in methods that should only return non-negative integers. -1是一个通用标志,用于指示应仅返回非负整数的方法失败。

I am having trouble calling this method in my main method. 我在主方法中调用此方法时遇到麻烦。 Does the problem lie in my getNextProjectIndex method or my main method in how I am calling it? 问题出在我的getNextProjectIndex方法还是我的主要方法中?

  public double getNextProjectIndex()
  {
    int i = 0;
    int full = -1;
    while(i < projects.length)
    {
      if (projects[i] == -1)
      {

        return i;
      }
      else if (i == (projects.length - 1) && projects[i] != -1)
      {
        return full;
      }

    }

    return i;

  }

Here is my main method: 这是我的主要方法:

public class Main {

  public static void main(String [ ] args)
  {
    Student testStudent = new Student("BL", "Hill", 34);
    int i = 0;
    System.out.println(testStudent.getFname() + " " + testStudent.getLname() );

    while(i < 5)
    {
      if(testStudent.getNextProjectIndex() != 0)
      {      
        testStudent.setProjectScore(10.0, i);
        System.out.println("Scores are: "+ testStudent.getProjectScore(i));
      }  


      i++;
    }


  }

}

When the program is run only one score is displayed rather than 5 scores. 运行该程序时,仅显示一个分数,而不显示5个分数。 It does not completely run through the loop. 它没有完全运行通过循环。 Only -1 should be returned from that method if ALL slots in the array are filled. 如果数组中的所有插槽均已填充,则只能从该方法返回-1。

Create a method named getNextProjectIndex() that returns an int 创建一个名为getNextProjectIndex()的方法,该方法返回一个int

You have declared your method as returning a double, even though the spec says to return an int, and you are attempting to return an int i in the function: 即使规范说要返回一个int,您也已声明您的方法返回一个double,并且您正在尝试在函数中返回一个int i

public double getNextProjectIndex()
       ^^^^^^

I am guessing that your program hangs. 我猜您的程序挂起了。 In the while loop in getNextProjectIndex() , i is never incremented, thus causing an infinite loop. getNextProjectIndex()while循环中, i从不增加,从而导致无限循环。

--Edit-- Also, you have some cruft in the method try: -编辑-另外,尝试方法还有一些不足之处:

public int getNextProjectIndex()
{
  int i = 0;
  while(i < projects.length) {
    if (projects[i] == -1)
      return i;
    ++i;
  }
  return -1;
}

--Edit-- changed to while loop, since that's apparently required. --Edit--更改为while循环,因为这显然是必需的。

似乎您没有在getNextProjectIndex中增加while循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM