Create a method named getNextProjectIndex() that returns an int that
gets the next index of the projects array that contains a -1.0. Find
the next item in the projects array that contains a -1.0 and return
that index of the array. This method should return -1 if the array is
full. -1 is a common flag to indicate failure in methods that should
only return non-negative integers.
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?
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. It does not completely run through the loop. Only -1 should be returned from that method if ALL slots in the array are filled.
I am guessing that your program hangs. In the
whileloop ingetNextProjectIndex(),iis never incremented, thus causing an infinite loop.–Edit–
Also, you have some cruft in the method try:
–Edit– changed to
whileloop, since that’s apparently required.