So I'm taking AP Computer Science A and I need some help I'm on Activity 28 and I have this question:
The removeExtension method is designed to input a name or 3-digit extension number (presented in the form of a String), and remove from the extensions array the first entry it finds that matches either the name or the extension (or both). If such a removal takes place, the size of the extensions array is reduced by 1.
As in Activity 27.1, a match should be registered when comparing names if the only difference is in the use of uppercase or lowercase letters. So "PETER" and "Peter" should match, while "Peter" and "Pete" should not.
Complete the definition of the removeExtension method:
public class MainClass{
public static PhoneExtension[] extensions = new PhoneExtension[]{
new PhoneExtension("Christine", "763"),
new PhoneExtension("Janice", "464"),
new PhoneExtension("Jon", "564"),
new PhoneExtension("Peter", "760"),
new PhoneExtension("Nicholas", "564"),
new PhoneExtension("Michael", "465"),
new PhoneExtension("Ryan", "564"),
new PhoneExtension("Pamela", "467"),
new PhoneExtension("Janice", "999"),
new PhoneExtension("Christine", "763")
};
public static void printDirectory(){
for (PhoneExtension ext : extensions)
System.out.println(ext);
}
public static void removeExtension(String t){
//My code starts here.
PhoneExtension[] temp = new PhoneExtension[extensions.length - 1];
int index;
for (int i = 0; i < extensions.length - 1; i++){
if (t.toLowerCase().equals(extensions[i].getName().toLowerCase()) || t.equals(extensions[i].getExtension())){
index = i;
continue;
}
}
for (int i = 0; i < index; i++){
temp[i] = extensions[i];
}
for (int i = index; i < temp.length - 1; i++){
temp[i + 1] = extensions[i];
}
extensions = temp;
//And ends here.
}
public static void main(String[] args){
removeExtension( "Peter" );
printDirectory();
}
}
This throws this error:
MainClass.java:75: error: variable index might not have been initialized
for (int i = 0; i < index; i++){
^
A few things to note are: the PhoneExtension class isn't shown but it has a getName and getExtension method that return it's name or extension. It's constructor looks like: PhoneExtension(String name, String extension). I don't know why we aren't using ArrayLists for this, seems like it could save some trouble but I could be missing something that is keeping us from using them...