Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

Troubleshooting
Research
Professional Opinions
Ask a Question
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

troubleshooting Question

Priority Queue implementation

Avatar of OwenMoriarty
OwenMoriartyFlag for Ireland asked on
HardwareJava
4 Comments1 Solution1003 ViewsLast Modified:
I have 3 classes and a main:
Heap
Patient
PQType
Hospital
The purpose is to create a queue of patients with an assigned priority, in the GUI I input the name and a priorty (String,Int) and so create a Patient object. I then enQueue it and then I want to print the heap to a string and set the string to a JTextArea.
My problem comes when I run the line in PQType:
        contents += items.elements[i].name + "\n";

I get
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at PQType.printPQ(PQType.java:51)
        at Hospital.newPatButtonActionPerformed(Hospital.java:157)


Any ideas?

Thanks,
Owen.

#####
 
public class Heap{
    Patient[] elements;
    int numElements;
    
 
    //constructor
    public Heap(int maxSize)
    {
        elements = new Patient[maxSize];
        numElements = maxSize;
    }//end default constructor
    public int getSize()
    {
        return elements.length;
    }
 
    public void ReheapUp(int root, int bottom)
    {
        int parent;
        if(bottom > root)        //if we reach top of the heap then stop
        {
            parent = (bottom - 1)/2;
            if (elements[parent].priority < elements[bottom].priority)
            {
                Swap(elements, parent, bottom); //swap method tbd
                ReheapUp(root,parent);
            }//end inner if
        }//end if
    }//end reheapup
 
    public void ReheapDown(int root, int bottom)
    {
        int maxchild, rightchild, leftchild;
        leftchild = root*2+1;
        rightchild = root*2+2;
 
        if(leftchild<=bottom)
        {
            if(leftchild == bottom)
                maxchild = leftchild;
            else
            {
                if(elements[leftchild].priority <= elements[rightchild].priority)
                    maxchild = rightchild;
                else
                    maxchild = leftchild;
            }//end else
 
            if(elements[root].priority < elements[maxchild].priority)
            {
               Swap(elements, root, maxchild);
               ReheapDown(maxchild, bottom);
            }//end if
        }//end outer if
    }//end reheapDown
    public void Swap(Patient[] anarray, int anIndex, int anotherIndex)
    {
        Patient temp;
        temp = anarray[anIndex];
        anarray[anIndex] = anarray[anotherIndex];
        anarray[anotherIndex] = temp;
    }
    
}//end class heap
#####
public class PQType
{
    private int numItems, maxItems;
    private Heap items;
    String contents = "";
 
    public PQType(int max)
    {
        items = new Heap(max);
        maxItems = max;
        numItems = 0;
    }//end default constructor
    public void makeEmpty()
    {
        numItems = 0;
    }//end make empty
 
    public void deQueue(Patient item)
    {
        item = items.elements[0];
        items.elements[0] = items.elements[numItems -1 ];
        numItems--;
        items.ReheapDown(0, numItems - 1);
    }//end dequeue
 
    public void enQueue(Patient newItem)
    {
        numItems++;
        items.elements[numItems - 1] = newItem;
        items.ReheapUp(0,numItems - 1);
    }// end enqueue
    public boolean isEmpty()
    {
        if (numItems < 0)
            return true;
        else
            return false;
    }//end is empty
    public boolean isFull()
    {
        System.out.println(items.getSize());
        System.out.println(items.elements[0].name);
        System.out.println(numItems);
        if ( numItems+1 == items.getSize())//dum de dum dum
            return true;
        else
            return false;
    }//end is full
    public String printPQ(String content)
    {
        System.out.println(items.getSize() + "From PQ");
        for (int i = 0;i < items.getSize()-1 ; i++)
        contents += items.elements[i].name + "\n";
        contents += "end of Queue";
        return contents;
    }
 
}//end class pqtype
#####
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
public class Hospital extends javax.swing.JFrame {
int pr;
String contents = "";
 
PQType myQueue = new PQType(6);
    /** Creates new form Hospital */
    public Hospital() {
        initComponents();
        waitingJTA.setText("Quiet Day so far");
        //myQueue.makeEmpty();
    }
 
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    //@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
 
        pNameTXT = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        pPriorityTXT = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        newPatButton = new javax.swing.JButton();
        callPatButton = new javax.swing.JButton();
        pNameCalledTXT = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        waitingJTA = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jLabel1.setText("Patient Name:");
 
        jLabel2.setText("Priority:");
 
        newPatButton.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        newPatButton.setText("New Patient");
        newPatButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newPatButtonActionPerformed(evt);
            }
        });
 
        callPatButton.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        callPatButton.setText("Call Patient");
 
        jLabel3.setText("Calling:");
 
        waitingJTA.setColumns(20);
        waitingJTA.setRows(5);
        jScrollPane1.setViewportView(waitingJTA);
 
        jLabel4.setBackground(new java.awt.Color(204, 204, 204));
        jLabel4.setFont(new java.awt.Font("Arial Narrow", 1, 12)); // NOI18N
        jLabel4.setText("Waiting List");
 
        jLabel5.setBackground(new java.awt.Color(204, 204, 204));
        jLabel5.setFont(new java.awt.Font("Arial Black", 1, 14)); // NOI18N
        jLabel5.setText("A&E Queue");
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel1))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(18, 18, 18)
                                        .addComponent(newPatButton, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(callPatButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(pPriorityTXT, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE)
                                            .addComponent(pNameTXT, javax.swing.GroupLayout.DEFAULT_SIZE, 225, Short.MAX_VALUE)))))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(155, 155, 155)
                                .addComponent(jLabel4))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(29, 29, 29)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel3)
                                        .addGap(22, 22, 22)
                                        .addComponent(pNameCalledTXT, javax.swing.GroupLayout.PREFERRED_SIZE, 217, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(193, 193, 193)
                        .addComponent(jLabel5)))
                .addGap(91, 91, 91))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(pNameTXT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(pPriorityTXT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(callPatButton)
                    .addComponent(newPatButton))
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pNameCalledTXT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
 
        pack();
    }// </editor-fold>                        
 
    private void newPatButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        if(myQueue.isFull())
        {
            newPatButton.setEnabled(false);
        }
        System.out.println("new patient button pressed");
        String nm = pNameTXT.getText();
        try{
                pr = Integer.valueOf(pPriorityTXT.getText());
            }  // End of try block
                catch (NumberFormatException e){
                    JOptionPane.showMessageDialog(rootPane, "Priorty must be a number");
                    return;
               }
        Patient np = new Patient(pr,nm);
        myQueue.enQueue(np);
        myQueue.printPQ(contents);
        waitingJTA.setText(contents);
}                                            
 
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Hospital().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify                     
    private javax.swing.JButton callPatButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton newPatButton;
    private javax.swing.JTextField pNameCalledTXT;
    private javax.swing.JTextField pNameTXT;
    private javax.swing.JTextField pPriorityTXT;
    private javax.swing.JTextArea waitingJTA;
    // End of variables declaration                   
 
}
#####
public class Patient{
 
    public int priority;
    public String name;
 
    public Patient(int p, String n)
    {
        if (p>5)
            p=5;
        if (p<1)
            p=1;
 
        priority = p;
        name = n;
 
    }//end default constructor
 
}//end class patient
#####
 
end code...
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick BarryFlag of Australia imageJava Developer
Commented:
This problem has been solved!
Unlock 1 Answer and 4 Comments.
See Answers