1

I am trying to sort an array of created objects each time an object is added. I wrote a compareTo method, and it is printing out each line, but throws an exception when I try to sort it. I am initializing an Element[] of 99 elements(maxLen), then using topIndex as a counter to find the "real" length. A scanner is used to get user input to create the Element. EDIT-- I added the full code.

import java.util.Arrays;
import java.util.Scanner;



public class mainmenu {
static Element[] data = new Element[100];
static int maxLen= 99; 
static int topIndex= -1;
@SuppressWarnings("rawtypes")


public static void main(String[] args){


    menu();


}


public static void menu(){
    boolean leave = true;
    Scanner in = new Scanner(System.in);
    while(leave){
        //loop. unless value is 1-7, keeps recycling    
        System.out.println("Please select a menu option: ");
        System.out.println("'1'- enque ");
        System.out.println("'2'- deque");
        System.out.println("'3'- peek");
        System.out.println("'4'- display");
        System.out.println("'5' empty queue");
        System.out.println("'6'- check if the queue is empty");
        System.out.println("'7' to exit the program");
        String select = in.next();
        if ((select.equals("1") || select.equals("2")|| select.equals("3")|| select.equals("4")|| 
                select.equals("5")|| select.equals("6")|| select.equals("7")))
            leave = callMethods(select );
        else{
            System.out.println("Please enter a valid menu option.");
        }
    }
}

public static  boolean callMethods(String select )
{
    boolean leave= true;
    int sel = Integer.parseInt(select);

    switch(sel){
    case 1:

        enqueue();

        break;
    case 2:
        dequeue();
        break;
    case 3:
        peek();

        break;
    case 4:
        display();

        break;
    case 5:
        empty();

        break;
    case 6:
        if( isEmpty()){
            System.out.println("The structure is empty");
        }
        else{
            System.out.println("The structure is not empty.");
        }
        break;
    case 7:
        System.out.println("Bye!");
        leave = false;
    }
    return leave;
}

public static void enqueue(){
    boolean isInt = false;
    String st = null;
    int index = 0;
    Scanner in = new Scanner(System.in);

    while(!isInt){  //loop continues until input is an integer type
        System.out.println("Please enter a priority level for this element");
        st = in.next();
        if (isInteger(st) == true){// calls method to check if value is integer
            index = Integer.parseInt(st);//parses the string into a integer
            isInt = true;
        }
        else //if value isnt integer, try again
            System.out.println("Invalid Input.");
    }
    System.out.println("Please enter the string of information.");
    String info = in.next();

    Element e = new Element(info, index);

    if (topIndex == maxLen){
        System.out.println("Data Structure is full.");
    }
    else if (isEmpty()){
        data[0] = e;
        topIndex++;
    }
    else {
        topIndex++;
        data[topIndex]=e;
        System.out.println("Added "+ e.getPriority() + " at "+ e.getInfo());
        System.out.println(topIndex);

        Arrays.sort(data);

    }

}

private static boolean isInteger(String s) {
    //checks to see if string can be parsed as an integer.


    try{
        Integer.parseInt(s);
        return true;
    }
    catch( Exception e ){
        return false;
    }


}
public static void dequeue(){
    if(isEmpty()){
        System.out.println("The structure is empty.");
    }
    else{
        Element e = data[topIndex];
        System.out.println("Removing Element: " + e.getInfo()+ " Priority Level: " + e.getPriority());
        --topIndex;
    }
}

public static void peek(){
    if (isEmpty()){
        System.out.println("The structure is empty.");

    }
    else {
        Element e = (data[0]);
        System.out.println("Element: " +  e.getInfo()+ " Priority Level: " + e.getPriority());
    }
}

public static void display(){
    System.out.println("topIndex " + topIndex);
    if (topIndex==-1){
        System.out.println("The structure is empty.");

    }
    else {
        for(int i = 0; i <= topIndex; i++){
            System.out.println("Index: " +i);
            Element e = data[i];
            System.out.println("Element: " + e.getInfo()+ " Priority Level: " + e.getPriority());

        }
    }
}

public static void empty(){
    System.out.println("Erasing data.");
    topIndex=-1;
}

public static boolean isEmpty(){
    return (topIndex==-1);
}

}

And the Element class:

public class Element implements Comparable<Element>  {

private String info;
private int index;

public Element ( String st, int ind) {
    super();
    this.info = st;
    this.index= ind;

}


public String getInfo() {
    return info;
}
public void setInfo(String st) {
    this.info = st;
}

public int getPriority(){
    return index;
}
public void setPriority(int pr){
this.index = pr;
}


public int compareTo(Element e) {
    System.out.println(e.index+ ""+ e.info);
//  if (!(e instanceof Element))
//      throw new ClassCastException("An Element object expected.");
    int ePriority = e.getPriority();  
    System.out.println(ePriority);
    System.out.println(this.index);
    int balls= this.index - ePriority;    
    System.out.println(balls);
    return balls;
}

}

5
  • 3
    What's the exception it's throwing? I guess it's a null pointer. Is the code you've given above the complete one? The main part doesn't loop through, that means it does only one iteration? Commented Dec 2, 2013 at 2:38
  • 1
    Why are you calling super() on an object that doesn't inherit from another object...? Commented Dec 2, 2013 at 2:39
  • It will throw the Element object expected exception I wrote in. If I comment out the throw declaration in the compareTo method, I get a null pointer exception. Commented Dec 2, 2013 at 2:40
  • Makato- I used to have the list created in a separate class, but ended up moving away from that. Commented Dec 2, 2013 at 2:41
  • 1
    ...but unless it extended that list's class (which would be even weirder still), then there'd be no reason to call super(). It's a code smell; nothing more, nothing less. Commented Dec 2, 2013 at 2:44

4 Answers 4

3

Arrays.sort requires all of the array elements to be non-null. You want to sort only the non-null part, so replace Array.sort(data) with Arrays.sort(data, 0, topIndex + 1).

Arrays.sort(Object[], int, int)

Do not modify compareTo to allow a null argument as others have suggested, because the contract of Comparable dictates that your implementation should throw NullPointerException.

Comparable.compareTo(T)

Sign up to request clarification or add additional context in comments.

1 Comment

Chris-Thanks! I knew it had to be something simple like that that. Work perfectly.
3

You have given Element[] array data to Array.sort() method which has size 100, but all of the element of data array are not initialized. Hence a call such as e.getPriority(); will result in NullPointerException as e is null. Initialize all of the element of data array first.

for(int i=0 ; i< data.length; i++)
   e = new Element(info, index); // replace with relevant info and index of your contest

Use Arrays.sort(Object[] array, int fromIndexInclusive, int toIndexExclusive) to sort parts of an array if needed:

Arrays.sort(data, 0, topIndex+1);

Comments

1

From your error description I would guess the Element object is getting null.

As per your comment

It will throw the Element object expected exception I wrote in. If I comment out the throw declaration in the compareTo method, I get a null pointer exception.

if (!(e instanceof Element))
    throw new ClassCastException("An Element object expected.");

The above statement will throw the exception only the object e is NULL

Comments

0

When doing a comparison, you're deciding if one object outranks another by some arbitrary condition.

I notice that you don't check if the object you're comparing against is null - you should do that.

public int compareTo(Element e) {
    if(e == null) {
        return this.index;
    } else {
        // rest of your logic goes here
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.