[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 449
  • Last Modified:

Java Null Pointer Exception issue

Hi,
I am also finished with this program, but I am now getting a null pointer exception in my dispInfo() area. I am stuck!

Thanks in advanced!!

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.text.NumberFormat;
import javax.swing.ImageIcon;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class Main extends JFrame
{
    private JButton firstButton = new JButton("First");
    private JButton prevButton = new JButton("Prev");
    private JButton nextButton = new JButton("Next");
    private JButton lastButton = new JButton("Last");
    private JButton calcButton = new JButton("Calculate");

    private JButton addButton = new JButton("Add");
    private JButton delButton = new JButton("Delete");
    private JButton resetButton = new JButton("Reset");
    private JButton btnSave = new JButton("Save");
    private JButton btnSearch = new JButton("Search");

    private JLabel lblnone = new JLabel("");
    private JLabel lblfname = new JLabel("First Name:");
    private JTextField txtfname = new JTextField(5);
    private JLabel lbllname = new JLabel("Last name:");
    private JTextField txtlname = new JTextField(5);
    private JLabel lblPhone = new JLabel("Phone:");
    private JTextField txtPhone = new JTextField(5);
    private JLabel lblloanAmount = new JLabel("Loan Amount:");
    private JTextField txtloanAmount = new JTextField(5);
    private JLabel lblinterestRate = new JLabel("Interest Rate:");
    private JTextField txtinterestRate = new JTextField(5);
    private JLabel lbltermYears = new JLabel("Terms in Months");
    private JTextField txttermYears = new JTextField(5);
    private JLabel lblmonthlyPayment = new JLabel("Monthly Payment");
    private JTextField txtmonthlyPayment = new JTextField (5);
    
         

    // currency NumberFormat
    private NumberFormat numFormat = NumberFormat.getCurrencyInstance();

    // create an array of Customers
    private counters[] Cust;

    // current index
    private int index = 0;

    // constructor
    public Main(counters[] individuals)
    {
        // add buttons to panel
        JPanel pnBtn = new JPanel();
        pnBtn.setLayout(new FlowLayout());
       // pnBtn.add(logo);
        pnBtn.add(firstButton);
        firstButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                index = 0;
                dispInfo();
            }
        });
        pnBtn.add(prevButton);
        prevButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if (--index < 0)
                    index = Cust.length - 1;
                dispInfo();
            }
        });
        pnBtn.add(nextButton);
        nextButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if (++index == Cust.length)
                    index = 0;
                dispInfo();
            }
        });
        pnBtn.add(lastButton);
        lastButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                index = Cust.length - 1;
                dispInfo();
            }
        });

        pnBtn.add(calcButton);
        calcButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    onCalcButtonClick(e);
                }
            });

        // add new buttons to panel
        JPanel pnBtn2 = new JPanel();
        pnBtn2.setLayout(new FlowLayout());
        pnBtn2.add(addButton);
        addButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                onBtnAdd();
            }
        });
        pnBtn2.add(delButton);
        delButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                onBtnDelete();
            }
        });
        pnBtn2.add(resetButton);
        resetButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                onresetButton();
            }
        });
        pnBtn2.add(btnSave);
        btnSave.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                onBtnSave();
            }
        });
        pnBtn2.add(btnSearch);
        btnSearch.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                onBtnSearch();
            }
        });

        // add labels and text fields to panel
        JPanel pnText = new JPanel();
        pnText.setLayout(new GridLayout(5, 2));
        pnText.add(new JLabel(new ImageIcon("C:/Users/Heather/Documents/UoP/Java_IT215/Week 8/may8th/src/may8th/logo.jpg"), JLabel.LEFT));
        pnText.add(lblfname);
        pnText.add(txtfname);
        pnText.add(lblnone);
        pnText.add(lbllname);
        pnText.add(txtlname);
        pnText.add(lblPhone);
        pnText.add(txtPhone);
        pnText.add(lblloanAmount);
        pnText.add(txtloanAmount);
        pnText.add(lblinterestRate);
        pnText.add(txtinterestRate);
        pnText.add(lbltermYears);
        pnText.add(txttermYears);
        pnText.add(lblmonthlyPayment);
        pnText.add(txtmonthlyPayment);
        

        // add 3 panels to main frame
        setLayout(new BorderLayout());
        add(pnBtn, BorderLayout.NORTH);
        add(pnText, BorderLayout.CENTER);
        add(pnBtn2, BorderLayout.SOUTH);

        setDefaultCloseOperation(EXIT_ON_CLOSE);

        Cust = individuals;

        // display current individual
        dispInfo();

        setSize(400, 600);
    } 

    // find counters index
    private int findIndex(counters indiv, counters[] arrayIndivs)
    {
        for (int i = 0; i < arrayIndivs.length; i++)
        {
            if (arrayIndivs[i] == indiv)
            {
                return i;
            }
        }
        return -1;
    } // end findIndex

    // save to file
    private boolean saveAll(boolean except)
    {
        FileWriter fw = null;
        try
        {
            fw = new FileWriter("c:\\data\\customer.dat");
            int size = isEmpty() ? 0 : Cust.length;

            for (int i = 0; i < size; i++)
            {
                // write counters to file
                fw.write(Cust[i].toString());
                fw.write( "\n" );
            }
            fw.close();
        } catch (Exception ex)
        { // if except is true, then try to create directory and saveAll again
            if (except)
            {
                new File("c:\\data\\").mkdir(); // create directory if does not exist
                return saveAll(false);
            }
            // if except is false, failed to save to file
            return false;
        }

        return true;
    } // end saveAll

    //handler for calc button

    public void onCalcButtonClick(ActionEvent e) {

        double loanAmount;
        double interestRate;
        double termYears;

        
            loanAmount = Double.parseDouble(txtloanAmount.getText());
             termYears = Double.parseDouble(txttermYears.getText());
            interestRate = Double.parseDouble(txtinterestRate.getText()) / 100;

            
        //Calculate monthly payment
        double payment = calculatePayment(loanAmount, termYears, interestRate);
        txtmonthlyPayment.setText(new Double(payment).toString());
    }

    public double calculatePayment(double loanAmount, double termYears,
        double interestRate) {
        double monthlyInterest = interestRate / 12;
        double monthlyPayment = (double) (loanAmount * (monthlyInterest / (1 -
            Math.pow(1 + monthlyInterest, termYears * -1))));
        monthlyPayment = Math.ceil(monthlyPayment * 100) / 100;

        return monthlyPayment;
    }


    // event handler for button Add
    private void onBtnAdd()
    {
        // create new counters
        counters newIndiv = loadIndividual(null);
        if (newIndiv == null)
            return;

        // copy old data to new array
        int oldSize = isEmpty() ? 0 : Cust.length;
        counters[] newArray = new counters[oldSize + 1];
        for (int i = 0; i < oldSize; i++)
            newArray[i] = Cust[i];
        newArray[oldSize] = newIndiv;
        // sort by name
        counters.sort(newArray);

        // display new counters
        index = findIndex(newIndiv, newArray);
        Cust = newArray;
        
        dispInfo();


    } // end onBtnAdd

    // event handler for button Delete
    private void onBtnDelete()
    {
        if (isEmpty())
            return;
        if (Cust.length == 1)
        {
            Cust = null;
            index = 0;
        }
        else
        {
            // delete current counters, and create a new array to store data
            counters[] newArray = new counters[Cust.length - 1];
            // copy data to new array
            for (int i = 0, j = 0; i < Cust.length; i++)
            {
                if (i != index)
                {
                    newArray[j] = Cust[i];
                    j++;
                }
            }
            Cust = newArray;
            if (index == Cust.length)
                --index;
        }

        // display current information

        dispInfo();

    } // end onBtnDelete

    // reset button
    private void onresetButton()
    {
    txtfname.setText("");
    txtlname.setText("");
    txtPhone.setText("");
    txtloanAmount.setText("");
    txtinterestRate.setText("");
    txttermYears.setText("");
    txtmonthlyPayment.setText("");

       
        dispInfo();

    } 

    // save button
    private void onBtnSave()
    {
        if (saveAll(true))
            JOptionPane.showMessageDialog(this, "Succeeded to save to file!");
        else
            JOptionPane.showMessageDialog(this, "Failed to save to file.");
    } 

    // search button
    private void onBtnSearch()
    {
        if (isEmpty())
            return;
        String name = JOptionPane.showInputDialog(this, "Please enter the name: ", "Search Individual", JOptionPane.INFORMATION_MESSAGE);
        if (name == null || name.isEmpty())
            return;
        counters temp = null;
        for (int i = 0; i < Cust.length; i++)
        {
            if (Cust[i].getlname().equals(name))
            {
                temp = Cust[i];
                break;
            }
        }
        if (temp == null)
        {
            JOptionPane.showMessageDialog(this, "Cannot find individual \"" + name + "\"!");
        }
        else
        {
            String text = "Individual \"" + name + "\":\n";
            text += temp.toString();
            JOptionPane.showMessageDialog(this, text, "Search Individual", JOptionPane.PLAIN_MESSAGE);
        }

    } 


    // display customer info
    private void dispInfo()
    {
        if (isEmpty())
        {
            txtfname.setText("");
            txtlname.setText("");
            txtPhone.setText("");
            txtloanAmount.setText("");
            txtinterestRate.setText("");
            txttermYears.setText("");

        }
        else
        {
            counters cur = Cust[index];
            txtfname.setText(cur.getfname());  // Null Pointer Exception here!!
            txtlname.setText(cur.getlname());
            txtPhone.setText(cur.getPhoneNumber());
            txtloanAmount.setText(Double.toString(cur.getloanAmount()));
            txtinterestRate.setText(Double.toString(cur.getinterestRate()));
            txttermYears.setText(Integer.toString(cur.gettermYears()));
       }
    } 

  
    private boolean isEmpty()
    {
        return Cust == null || Cust.length == 0;
    } 

    // user input
    public static counters loadIndividual(counters old)
    {
        String init = "";

        
        String fname;
        do
        {
            init = (old == null) ? "" : old.getfname();
            fname = JOptionPane.showInputDialog("First name: ", init);
            if (fname == null)
                return null;
        } while (fname.isEmpty());


        
        String lname;
        do
        {
            init = (old == null) ? "" : old.getlname();
            lname = JOptionPane.showInputDialog("Last name ", init);
            if (lname == null)
                return null;
        } while (lname.isEmpty());


        
        String phone;
        do
        {
            init = (old == null) ? "" : ("" + old.getPhoneNumber());
            phone = JOptionPane.showInputDialog("Phone number: ", init);
            if (phone == null)
                return null;
        } while (phone.isEmpty());
        return null;




            }
    

    // input from user
    public static counters[] loadData()
    {
        counters[] Cust = new counters[7];
        // count 1-5
        for (int count = 1; count <= Cust.length; count++)
        {
            counters indiv = loadIndividual(null);
            if (indiv == null)
                return null;
            Cust[count - 1] = indiv;
        }

        // sort by name
        counters.sort(Cust);

        return Cust;
    } 

    // main method
    public static void main(String[] args)
    {
       // counters[] indivs = loadData();
       //if (indivs == null)
       //    return;

   
       counters[] Cust = new counters[7];
   
     

        Main gui = new Main(Cust);
        gui.setVisible(true);

    } 

} 


----- the other files in case needed:

import java.text.NumberFormat;

/**
 *
 * @author Heather
 */

public class getters
{
    private String fname;
    private String lname;
    private int number;
    private double loanAmount;
    private double interestRate;
    private int termYears;
    private double monthlyPayment;


    // constructors
    public getters(String nm, String lna, int num, double loanA, double interestR, int termY, double monthlyP)
    {
        fname = nm;
        lname = lna;
        number = num;
        loanAmount = loanA;
        interestRate = interestR;
        termYears = termY;
        monthlyPayment = monthlyP;
    } 

    
    public String getfname()
    {
        return fname;
    } 

    
    public void setName(String fname)
    {
        this.fname = fname;
    } 

    
    public String getlname()
    {
        return lname;
    } 

    
    public void setAddress(String lname)
    {
        this.lname = lname;
    } 

    
    public int getNumber()
    {
        return number;
    } 

    
    public void setNumber(int number)
    {
        this.number = number;
    } 

    
    public double getloanAmount()
    {
        return loanAmount;
    } 

   
    public void setloanAmount(double loanAmount)
    {
        this.loanAmount = loanAmount;
    } 

    public double getinterestRate()
    {
        return interestRate;
    }

    public void setinterestRate(double interestRate)
    {
        this.interestRate = interestRate;
    }

        public int gettermYears()
    {
        return termYears;
    }


    public void settermYears(int termYears)
    {
        this.termYears = termYears;
    }

            public double getmonthlyPayment()
    {
        return monthlyPayment;
    }

    public void setmonthlyPayment(double monthlyPayment)
    {
        this.monthlyPayment = monthlyPayment;
    }


} 

-------and:

import java.text.NumberFormat;

public class counters extends getters
{
    private static NumberFormat numFormat = NumberFormat.getCurrencyInstance();

    private String phoneNumber;

    
    public counters(String nm, String lna, int num, double loanA, double interestR, int termY, double monthlyP,
            String phone)
    {
        super(nm, lna, num, loanA, interestR, termY, monthlyP);
        phoneNumber = phone;
    } 


    
    public String getPhoneNumber()
    {
        return phoneNumber;
    } 

    
    public void setPhoneNumber(String phoneNumber)
    {
        this.phoneNumber = phoneNumber;
    } 

    
    public String toString()
    {
        String s = "";
        s += ("First Name:" + getfname() + "\n" );
        s += ("Last Name:" + getlname() + "\n");
        s += ("Phone:" + getPhoneNumber() + "\n" );
        return s;
    } 

    
    public static void sort(counters[] persons)
    {
        // Bubble Sort
        counters Temp;
        for (int j = persons.length - 1; j >= 1; j--)
        {
            for (int i = 0; i < j; i++)
            {
                if (persons[i + 1].getfname().compareTo(persons[i].getfname()) < 0)
                {
                    Temp = persons[i];
                    persons[i] = persons[i + 1];
                    persons[i + 1] = Temp;
                }
            } 
        } 
    } 

}

Open in new window

0
marchbaby
Asked:
marchbaby
  • 4
  • 3
1 Solution
 
CEHJCommented:
You don't initialize an instance of getters so it can return any details
0
 
CEHJCommented:
Sorry - i meant 'counters'
0
 
CEHJCommented:
>>    
// main method
    public static void main(String[] args) {
        // counters[] indivs = loadData();
        //if (indivs == null)
        //    return;
        counters[] Cust = new counters[7];

        Main gui = new Main(Cust);
        gui.setVisible(true);
    }
>>

There's an empty array of counters with no instance in it. The trouble is

>>txtfname.setText(cur.getfname()); // Null Pointer Exception here!!

tries to use a non-existent instance
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
marchbabyAuthor Commented:
OK, I understand but not sure what I need to change to make it different...
0
 
marchbabyAuthor Commented:
i am really lost here.....
0
 
marchbabyAuthor Commented:
I fixed it! Thanks!!
0
 
CEHJCommented:
:)
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now