ed2101 ed2101 - 1 month ago 6
Java Question

Java error "Cannot find symbol - method(validIndex)"

I am working through an assignment for my course. I was asked to create a valid index method that checked whether the int entered was a valid index for my ArrayList. This method compiled fine and worked fine.

A further exercise asked me to then use this validIndex method within other methods. I have tried to do that within my removeFile method. The removeFile method is meant to call the validIndex method in order to check whether the index parameter of removeFile is a valid index for the ArrayList. However my file now refuses to compile giving me the error


cannot find symbol - method validIndex()


The code is below:

import java.util.ArrayList;

/**
* A class to hold details of audio files.
*
* @author David J. Barnes and Michael Kölling
* @version 2011.07.31
*/
public class MusicOrganizer
{
// An ArrayList for storing the file names of music files.
private ArrayList<String> files;
/**
* Create a MusicOrganizer
*/
public MusicOrganizer()
{
files = new ArrayList<String>();
}

/**
* Add a file to the collection.
* @param filename The file to be added.
*/
public void addFile(String filename)
{
files.add(filename);
}

/**
* Return the number of files in the collection.
* @return The number of files in the collection.
*/
public int getNumberOfFiles()
{
return files.size();
}

/**
* List a file from the collection.
* @param index The index of the file to be listed.
*/
public void listFile(int index)
{
if(index >= 0 && index < files.size()) {
String filename = files.get(index);
System.out.println(filename);
}
}

/**
* Remove a file from the collection.
* @param index The index of the file to be removed.
*/
public void removeFile(int index)
{
if(files.validIndex() = true){
files.remove(index);
}
}

// Problem with this method. If ArrayList is empty then the indexes variable returns minus 1
public void checkIndex(int index)
{
int size = files.size();
int indexes = size - 1;
if (index >= 0 && index <= indexes){
System.out.println("");
}
else {
System.out.println("That is not a valid index number.");
System.out.println("The index should be between 0 and " + indexes);
}
}

public boolean validIndex(int index)
{

if (index >= 0 && index <= files.size()-1){
return true;
}
else {
return false;
}
}



}


If someone could point out why my code won't compile that would be appreciated.

Answer

If you are trying to call your own method validIndex, you are calling it wrong.

To call your validIndex method, you should do the following:

public void removeFile(int index)
    {
        if(this.validIndex(index)){
            files.remove(index);
        }
    }

The reason is that ArrayList does not have a "validIndex" method, so files.validIndex() won't work, validIndex is a method in your object.

Also, validIndex takes a parameter, the index, public boolean validIndex(int index), so you need to pass the index to the method when you call it.

Comments