I have a problem with this array:
public void dropCourse(String courseName)
{
String credits;
int numCredits;
int found;
int index;
found = searchToDelete(courseName);
if(found == -1)
System.out.println("Course was not found in the schedule");
else
{
credits = courseName.substring(courseName.length() - 1);
numCredits = Integer.parseInt(credits);
totalCredits -= 1;
if(found == courseName.length() - 1)
totalCourses -= 1;
else
{
for(index = found; index < totalCourses; index )
{
schedule[index] = schedule[index] 1;
}
totalCourses -= 1;
}
And this is the method searchToDelete that I am calling to this drop course method that I tested, which should be returning a integer value of 4 in that part of the String:
public int searchToDelete(String courseName)
{
boolean flag = false;
int index = 0;
int found = -1;
while(index < MAX_COURSES && flag == false)
{
String tempString = schedule[index].substring(0,6);
if(tempString.equals(courseName) == true)
flag = true;
else
index ;
}
if(flag == true)
found = index;
return found;
}
I've been looking at this code and not sure why it's saying OutOfBound length 6, I should also note that I was following my professor's algorithm/pseudo code for the most part of the dropCourse method. I, myself added the courseName.substring with the parse. Not sure what I'm doing wrong, would appreciate any sort of help, this is my first course for programming, so sorry for my ignorance.
Update, based on comment under one answer:
It says the line schedule[index] = schedule[index] 1;
is where it throws the error.
CodePudding user response:
as a guess i might say that the course stored in schedule[index] might be less than 6 characters long.
CodePudding user response:
The loop where you do the delete should look like this.
for(index = found; index < totalCourses - 1; index )
{
schedule[index] = schedule[index 1];
}
The idea is to replace the element at each position in the array, starting at found
with the element in the next position. But if you don't have the - 1
in the second clause of the for
loop, you get into trouble when you reach the end of the array, because you're looking to replace the last element with an element that doesn't exist.
CodePudding user response:
I don't know why exactly you need the substring end by the char number 6 but if you mean the end of the String you can use one of those peace of code below. (both ahave the same result)
String tempString = schedule[index].substring(0,courseName.length());
String tempString = schedule[index].substring(0);