Call a method from an other class located in another package which is already imported

StackOverflow https://stackoverflow.com/questions/23503554

  •  16-07-2023
  •  | 
  •  

Domanda

I am an Undergraduate Computer Science Student and we're actually starting to learn the Java Language. I am trying to solve one of my Labs but I have a problem. My Problem is how to call a method from an other class, which is located in another package, and the package is already imported in my class. I tried to write the nameOftheClass.nameOfthemethod(parameters); but that didn't work for me. To be more Specefic, I was trying to call the method getElementAt(index) which is located in the frame package and in the SortArray Class .. But I don't have a clue why is this not working for me!

this is my QuicksortB Class :

package lab;

import frame.SortArray;

public class QuickSortB extends QuickSort {

/**
 * Quicksort algorithm implementation to sort a SorrtArray by choosing the
 * pivot as the median of the elements at positions (left,middle,right)
 * 
 * @param records
 *            - list of elements to be sorted as a SortArray
 * @param left
 *            - the index of the left bound for the algorithm
 * @param right
 *            - the index of the right bound for the algorithm
 * @return Returns the sorted list as SortArray
 */
@Override
public void Quicksort(SortArray records, int left, int right) {
    // TODO
    // implement the Quicksort B algorithm to sort the records
    // (choose the pivot as the median value of the elements at position
    // (left (first),middle,right(last)))

    int i = left, j = right;
    //Get The Element from the Middle of The List
    int pivot = SortArray.getElementAt(left + (right-left)/2);

    //Divide into two Lists
    while (i <= j) {
        // If the current value from the left list is smaller then the pivot
        // element then get the next element from the left list
        while (SortArray.getElementAt(i) < pivot) {
            i++;
        }

        // If the current value from the right list is larger then the pivot
        // element then get the next element from the right list
        while (SortArray.getElementAt(j) > pivot) {
            j--;
        }

        // If we have found a values in the left list which is larger then
        // the pivot element and if we have found a value in the right list
        // which is smaller then the pivot element then we exchange the
        // values.
        // As we are done we can increase i and j

        if (i <= j) {
            exchange(i,j)
            i++;
            j--;
        }
    }

    public void exchange(int i, int j) {
        int temp = SortArray.getElementAt(i);
        SortArray.getElementAt(i) = SortArray.getElementAt(j);
        SortArraz.getElementAt(j) = temp;
    }

}

}

And this is My SortArray Class :

package frame;

import java.util.ArrayList;

import lab.SortingItem;

/**
 * Do NOT change anything in this class!
 * 
 * The SortArray class provides simple basic functions, to store a list of
 * sortingItems to track the number of operations.
 * 
 * This class contains two members (readingOperations and writingOperations)
 * that act as counters for the number of accesses to the arrays to be sorted.
 * These are used by the JUnit tests to construct the output. The methods
 * provided in this class should be sufficient for you to sort the records of
 * the input files.
 * 
 * @author Stefan Kropp
 */

public class SortArray {

    private int numberOfItems;

    private ArrayList<SortingItem> listOfItems;

    private int readingOperations;
    private int writingOperations;

    /**
     * @param numberOfItems
     *            number of items to hold
     */
    public SortArray(ArrayList<String[]> items) {
        numberOfItems = items.size();
        readingOperations = 0;
        writingOperations = 0;
        listOfItems = new ArrayList<>();

        for (String[] element : items) {
            SortingItem s = new SortingItem();
            s.BookSerialNumber = element[0];
            s.ReaderID = element[1];
            s.Status = element[2];
            listOfItems.add(s);
        }
    }

    /**
     * sets the elements at index. if index is >= numberOfItems or less then
     * zero an IndexOutOfBoundException will occur.
     * 
     * @param index
     *            the index of the Elements to set
     * @param record
     *            a 3-dimensional record which holds: BookSerialNumber,
     *            ReaderID, Status
     */
    public void setElementAt(int index, SortingItem record) {
        this.listOfItems.set(index, record);

        writingOperations++;
    }

    /**
     * Retrieves the information stored at position Index. if index is >=
     * numberOfItems or less then zero an IndexOutOfBoundException will occur.
     * 
     * @param index
     *            Index defines which elements to retrieve from the SortArray
     * @return Returns a 3-dimensional String array with following format:
     *         BookSerialNumber, ReaderID, Status.
     * 
     */
    public SortingItem getElementAt(int index) {

        SortingItem result = new SortingItem(this.listOfItems.get(index));
        readingOperations++;
        return result;
    }

    /**
     * @return Returns the number of reading operations.
     */
    public int getReadingOperations() {
        return readingOperations;
    }

    /**
     * @return Returns the number of writing operations.
     */
    public int getWritingOperations() {
        return writingOperations;
    }

    /**
     * @return Returns the numberOfItems.
     */
    public int getNumberOfItems() {
        return numberOfItems;
    }
}
È stato utile?

Soluzione

You attempted to call the method getElementAt as a static function. You have to create an instance of SortArray and then call the method on that object, e.g.

ArrayList<String[]> myList = ...; // some initialization

SortArray sortObject = new SortArray(myList);

SortingItem result = sortObject.getElementAt(0);

If you want your function to be accessible as you tried, you have to use the static modifier, which in turn means, you don't have access to members of the class (i.e. non-static fields).

public void doSomething() {
    this.numberOfItems++; // this is allowed
}

In contrast to:

public static void doSomethingStatic() {
    this.numberOfItems++; // this is not allowed
}

Altri suggerimenti

to call a method, you have to know if the method is static method (class method) or object method.

If it is static method, (like the famous main(String[] args)) you can just call it by ClassName.method(), if it is not static method, you have to first get the instance of the class, by calling the constructor for example, then call the method via oneInstance.method()

I suggest you reading the related chapters in your lecture text book, then do some test on your own.

I just don't give codes since this is an assignment.

The way you are trying to access the function is as if it were static, since you try to call it through the actual class, not from an object.

You should generate an object which references the desired class, in this case SortArray.

In QuickSortB

public SortArray sortArray;
@Override
public void Quicksort(SortArray records, int left, int right) {
    // TODO
    // implement the Quicksort B algorithm to sort the records
    // (choose the pivot as the median value of the elements at position
    // (left (first),middle,right(last)))
    sortArray = new SortArray ();
    int i = left, j = right;
    //Get The Element from the Middle of The List
    int pivot = sortArray.getElementAt(left + (right-left)/2);

    //Divide into two Lists
    while (i <= j) {
        // If the current value from the left list is smaller then the pivot
        // element then get the next element from the left list
        while (sortArray.getElementAt(i) < pivot) {
            i++;
        }

        // If the current value from the right list is larger then the pivot
        // element then get the next element from the right list
        while (sortArray.getElementAt(j) > pivot) {
            j--;
        }

        // If we have found a values in the left list which is larger then
        // the pivot element and if we have found a value in the right list
        // which is smaller then the pivot element then we exchange the
        // values.
        // As we are done we can increase i and j

        if (i <= j) {
            exchange(i,j)
            i++;
            j--;
        }
    }

    public void exchange(int i, int j) {
        int temp = SortArray.getElementAt(i);
        sortArray.getElementAt(i) = SortArray.getElementAt(j);
        sortArray.getElementAt(j) = temp;
    }
  }

}

Hope it helps^^

Create an instance of SortArray object and call using that reference check the below code for clarity

public class QuickSortB extends QuickSort {
//create instance of sortArray

SortArray sortArray=new SortArray();

//call the method like this

    sortArray.getElementAt(i)    

}

public class SortArray {

// code skipped for clarity


     public SortingItem getElementAt(int index) {

            SortingItem result = new SortingItem(this.listOfItems.get(index));
            readingOperations++;
            return result;
        }



// code skipped for clarity
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top