Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

java.lang.NullPointerException

Status
Not open for further replies.

kawika1975

IS-IT--Management
Dec 19, 2005
8
US
I am working on this mortgage calculator, the program compiles fine and all, however when I try to run the program I get a java.lang.NullPointerException. Could someone please take a look at the following code and advise me on what I did wrong?

/*********** Import Libraries **************************************/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.NumberFormat;
import java.util.Locale;
/*******************************************************************/

public class mortgageCalculator extends JFrame
{

/****** input limits **********************/
private static final double MIN_PRINCIPAL = 0.0;
private static final double MAX_PRINCIPAL = 1000000;
private static final double MIN_APR = 0;
private static final double MIN_TERM = 0.0;

/****** top level container ***************/
Container container;

/****** Grid Bag Components **************/
private GridBagLayout gridBagLayout;
private GridBagConstraints gridBagConstraints;

// Selected Mortgage Holder
private static Mortgage mortgagelist[];

// execute application
public static void main(String args[]) {
mortgageCalculator application = new mortgageCalculator();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

// constructor creates and launches the interface
public mortgageCalculator() {
super("Joe Blow Mortgage Calculator");

container = getContentPane();

//create a gridbag, which is a table that we can add GUI to each cell
//very similar to a Table in MS Word, you add panels to each
//cell and if necessary you can merge rows and columns

gridBagLayout = new GridBagLayout();
container.setLayout(gridBagLayout);
gridBagConstraints = new GridBagConstraints();

constructDirections();
constructInputField();
constructInputFieldRate();
constructInputFieldTerm();
constructCalculateButton();
constructMortgageSelection();

setSize(520, 520);
setVisible(true);

}

/*************************** Calculate Services *********************************/

/***** Button Components ************/
private JButton calculateButton;
private JPanel buttonPanel;
private ButtonHandler buttonHandler;

/****** Currency amount Components ************/
private JLabel amountLabel;

private void constructCalculateButton() {
buttonHandler = new ButtonHandler();
calculateButton = new JButton("Calculate Payment");
calculateButton.addActionListener(buttonHandler);

//create output label
amountLabel = new JLabel();
setFont(new Font("Arial", Font.BOLD + Font.ITALIC, 12));
amountLabel.setHorizontalAlignment(JLabel.LEFT); ;
amountLabel.setForeground(Color.BLUE);

//put inside a panel
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(2, 1));

//add the button, then the label to the panel
buttonPanel.add(calculateButton);
buttonPanel.add(amountLabel);

//add panel to the gridbag, third row, first column
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 10;

//put in the first column, of the second row
gridBagConstraints.gridwidth = 1;
gridBagConstraints.gridheight = 1;
gridBagConstraints.fill = GridBagConstraints.BOTH;

gridBagLayout.setConstraints(buttonPanel, gridBagConstraints);

//add the button group panel to the container
container.add(buttonPanel);

} // End constructCalculateButton()

private class ButtonHandler
implements ActionListener {
public void actionPerformed(ActionEvent event) {
double amount = 0.0;
double rate = 0;
double term = 0.0;
String currency = "";
boolean valid = false;
String errorPrompt = "";
String output = "";
// mortCalc1 mortageCalc;

// Create an instance of the menu
MenuBar mnuBar = new MenuBar();
setMenuBar(mnuBar);

// Construct and populate the File menu
Menu mnuFile = new Menu("File", true);
mnuBar.add(mnuFile);
MenuItem mnuFileExit = new MenuItem("Exit");
mnuFile.add(mnuFileExit);

// Construct and populate the Edit Menu
Menu mnuEdit = new Menu("Edit", true);
mnuBar.add(mnuEdit);
MenuItem mnuEditClear = new MenuItem("Clear");
mnuEdit.add(mnuEditClear);

// Construct and populate the About Menu
Menu mnuAbout = new Menu("About", true);
mnuBar.add(mnuAbout);
MenuItem mnuAboutMortgage = new MenuItem("About Mortgage Calculator");
mnuAbout.add(mnuAboutMortgage);

// Add the ActionListener to each menu item
mnuFileExit.addActionListener(this);
mnuEditClear.addActionListener(this);
mnuAboutMortgage.addActionListener(this);

// assign an ActionCommand to each menu item
mnuFileExit.setActionCommand("Exit");
mnuEditClear.setActionCommand("Clear");
mnuAboutMortgage.setActionCommand("About");

// Test for menu item clicks
String arg = event.getActionCommand();
if (arg == "Exit")
System.exit(0);

if (arg == "Clear") {
inputField.setText("");
inputFieldTerm.setText("");
inputFieldRate.setText("");
amountLabel.setText("");
}

if (arg == "About") {
String message =
"Mortgage Calculator ver. 1.0\nJoe Blow\nAll rights Reserved";
JOptionPane.showMessageDialog(null, message,
"About Mortgage Calculator",
JOptionPane.INFORMATION_MESSAGE);
}

if (event.getSource() == calculateButton) {

amount = Double.parseDouble(inputField.getText());

if (amount >= MIN_PRINCIPAL && amount <= MAX_PRINCIPAL) {
valid = true;
}
else {
valid = false;
errorPrompt = "Amount must be between " + MIN_PRINCIPAL + " and " +
MAX_PRINCIPAL;
JOptionPane.showMessageDialog(null,
errorPrompt,
"Invalid Amount",
JOptionPane.WARNING_MESSAGE);
}
rate = Double.parseDouble(inputFieldRate.getText());
term = Double.parseDouble(inputFieldTerm.getText());
if (valid && rate >= MIN_APR) {
//both amount input and rate are valid, so we can create a CurrencyCalculator
//object and calculate the currency

}
else {
valid = false;
errorPrompt = "Interest rate must be greater than or equal to " +
MIN_APR;
JOptionPane.showMessageDialog(null,
errorPrompt,
"Invalid Rate",
JOptionPane.WARNING_MESSAGE);

}

//at this point, output has been set to converted value or if an error
//condition occurred the ouput is an empty string
amountLabel.setText(output);
/*if (valid) {
//destroy the MortgageCalculator object
mortageCalc = null;
}*/
}
}
}

/*************************** Currency Input Services ****************************/

/****** User Input Components *****************/
private JLabel inputLabel;
private JTextField inputField;
private JPanel userInputpanel;

private void constructInputField() {
userInputpanel = new JPanel();
userInputpanel.setLayout(new GridLayout(1, 2));

inputLabel = new JLabel("Enter Principle: ");
inputLabel.setFont(new Font("Arial", Font.BOLD, 12));
inputLabel.setHorizontalAlignment(JLabel.LEFT);
inputField = new JTextField(10);

//set a default value
inputField.setText("");

//add the label in the first column
userInputpanel.add(inputLabel);

//add the text field in the second column
userInputpanel.add(inputField);

//add the panel to the gridbag
//first column, third row
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;

//put in the first column, of the second row
gridBagConstraints.gridwidth = 1;
gridBagConstraints.gridheight = 1;
gridBagConstraints.fill = GridBagConstraints.BOTH;

//create the first row
gridBagLayout.setConstraints(userInputpanel, gridBagConstraints);

//add the button group panel to the container
container.add(userInputpanel);

}

/****** User Input Components *****************/
private JLabel inputLabelRate;
private JTextField inputFieldRate;
private JPanel userInputpanelRate;

private void constructInputFieldRate() {

userInputpanelRate = new JPanel();
userInputpanelRate.setLayout(new GridLayout(1, 2));

inputLabelRate = new JLabel("Enter Rate: ");
inputLabelRate.setFont(new Font("Arial", Font.BOLD, 12));
inputLabelRate.setHorizontalAlignment(JLabel.LEFT);
/*inputFieldRate = new JTextField(10); */

inputFieldRate = new JTextField();
inputFieldRate.setText("");
inputFieldRate.setColumns(10);

//add the label in the first column
userInputpanelRate.add(inputLabelRate);

//add the text field in the second column
userInputpanelRate.add(inputFieldRate);

//add the panel to the gridbag
//first column, third row
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;

//put in the first column, of the second row
gridBagConstraints.gridwidth = 1;
gridBagConstraints.gridheight = 1;
gridBagConstraints.fill = GridBagConstraints.BOTH;

//create the first row
gridBagLayout.setConstraints(userInputpanelRate, gridBagConstraints);

//add the button group panel to the container
container.add(userInputpanelRate);
}

private JLabel inputLabelTerm;
private JTextField inputFieldTerm;
private JPanel userInputpanelTerm;

private void constructInputFieldTerm() {
userInputpanelTerm = new JPanel();
userInputpanelTerm.setLayout(new GridLayout(1, 2));

inputLabelTerm = new JLabel("Enter Years: ");
inputLabelTerm.setFont(new Font("Arial", Font.BOLD, 12));
inputLabelTerm.setHorizontalAlignment(JLabel.LEFT);
inputFieldTerm = new JTextField(10);

//set a default value
inputFieldTerm.setText("");

//add the label in the first column
userInputpanelTerm.add(inputLabelTerm);

//add the text field in the second column
userInputpanelTerm.add(inputFieldTerm);

//add the panel to the gridbag
//first column, third row
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 6;

//put in the first column, of the second row
gridBagConstraints.gridwidth = 1;
gridBagConstraints.gridheight = 1;
gridBagConstraints.fill = GridBagConstraints.BOTH;

//create the first row
gridBagLayout.setConstraints(userInputpanelTerm, gridBagConstraints);

//add the button group panel to the container
container.add(userInputpanelTerm);

}

/********************** Application Instruction Services ***********************/

private static final String title = " Mortgage Calculator, v1.0";

private static final String description =
"This is a program that allows the user to calculate his or her " +
"mortgage payment";

private static final String instructions = "Instructions:\n" +
"1. Enter Amount\n" +
"2. Enter Term\n" +
"3. Enter Rate\n" +
"4. Click on Calculate";

String menuStr;
private JTextArea instructionText;
private JPanel instructionPanel;

private void constructDirections() {
menuStr = title + "\n\n";
menuStr += description + "\n";
menuStr += instructions + "\n";

instructionText = new JTextArea(menuStr);
instructionText.setFont(new Font("Arial", Font.BOLD, 12));
instructionText.setBackground(Color.LIGHT_GRAY);

instructionPanel = new JPanel();
instructionPanel.setLayout(new GridLayout(1, 1));

instructionPanel.add(instructionText);

//add the instruction panel to the first cell, merge all the cells in the first row
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;

//span the first three columns in the first row
gridBagConstraints.gridwidth = 3;
gridBagConstraints.gridheight = 1;
gridBagConstraints.fill = GridBagConstraints.BOTH;

//create the first row
gridBagLayout.setConstraints(instructionPanel, gridBagConstraints);

//add the instruction panel to the container
container.add(instructionPanel);

}

private ButtonGroup defaultGroup;
private JRadioButton defaultOptions[] = new JRadioButton[NUMBER_MORTGAGE];
private JPanel defaultPanel;
RadioButtonHandler radioHandler;

private void constructMortgageSelection() {
defaultPanel = new JPanel();
defaultGroup = new ButtonGroup();
radioHandler = new RadioButtonHandler();

// create four rows of radio buttons
defaultPanel.setLayout(new GridLayout(NUMBER_MORTGAGE, 1));
for (int i = 0; i < NUMBER_MORTGAGE; i++) {
defaultOptions = new JRadioButton(mortgagelist.toString(), false);
defaultPanel.add(defaultOptions);
defaultGroup.add(defaultOptions);
defaultOptions.addItemListener(radioHandler);
}
// set the default selection to the first choice
defaultOptions[0].setSelected(true);

// add the radio button group to the gridbag
// first column, second row, spanning one cell of the row
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;

// put in first column, of the second row
gridBagConstraints.gridwidth = 1;
gridBagConstraints.gridheight = 1;
gridBagConstraints.fill = GridBagConstraints.BOTH;

// create the first row
gridBagLayout.setConstraints(defaultPanel, gridBagConstraints);

// add the button group panel to the container
container.add(defaultPanel);
} // end constructMortgageSelection

// handler for the radio buttons, which only keeps track
// of which button has been pressed and then makes a calculation

private class RadioButtonHandler
implements ItemListener {
public void itemStateChanged(ItemEvent event) {
if (event.getSource() == defaultOptions[0] &&
defaultOptions[0].isSelected()) {
double amount = Double.parseDouble(inputField.getText());
double rate = Double.parseDouble(inputFieldRate.getText());
double term = Double.parseDouble(inputFieldTerm.getText());
double monthlyInt = rate / (12 * 100);
double usValue = amount *
(monthlyInt /
(1 - java.lang.Math.pow( (1 + monthlyInt), ( -1 * term * 12))));
String strValue = "";
String output = "";
NumberFormat moneyFormat = NumberFormat.getCurrencyInstance(Locale.US);

strValue = moneyFormat.format(usValue);

output = "Your payment is: " + strValue;
}
else if (event.getSource() == defaultOptions[1] &&
defaultOptions[1].isSelected()) {
double amount = Double.parseDouble(inputField.getText());
double rate = .0535;
double term = 7;
double monthlyInt = rate / (12 * 100);
double usValue = amount *
(monthlyInt /
(1 - java.lang.Math.pow( (1 + monthlyInt), ( -1 * term * 12))));
String strValue = "";
String output = "";
NumberFormat moneyFormat = NumberFormat.getCurrencyInstance(Locale.US);

strValue = moneyFormat.format(usValue);

output = "Your payment is: " + strValue;
}
else if (event.getSource() == defaultOptions[2] &&
defaultOptions[2].isSelected()) {
double amount = Double.parseDouble(inputField.getText());
double rate = .055;
double term = 15;
double monthlyInt = rate / (12 * 100);
double usValue = amount *
(monthlyInt /
(1 - java.lang.Math.pow( (1 + monthlyInt), ( -1 * term * 12))));
String strValue = "";
String output = "";
NumberFormat moneyFormat = NumberFormat.getCurrencyInstance(Locale.US);

strValue = moneyFormat.format(usValue);

output = "Your payment is: " + strValue;
}
else if (event.getSource() == defaultOptions[3] &&
defaultOptions[3].isSelected()) {
double amount = Double.parseDouble(inputField.getText());
double rate = .0575;
double term = 30;
double monthlyInt = rate / (12 * 100);
double usValue = amount *
(monthlyInt /
(1 - java.lang.Math.pow( (1 + monthlyInt), ( -1 * term * 12))));
String strValue = "";
String output = "";
NumberFormat moneyFormat = NumberFormat.getCurrencyInstance(Locale.US);

strValue = moneyFormat.format(usValue);

output = "Your payment is: " + strValue;
}
}
}

// Predefined Mortgages
private static final int NUMBER_MORTGAGE = 3;

private void createMortgageList() {
mortgagelist = new Mortgage[NUMBER_MORTGAGE];

mortgagelist[0] = new Mortgage(0, "Input my own");
mortgagelist[1] = new Mortgage(1, "7 year at 5.35%");
mortgagelist[2] = new Mortgage(2, "15 year at 5.5%");
mortgagelist[3] = new Mortgage(3, "30 year at 5.75%");

}
 
Learn to help yourself by helping others to help you first.
You say you have a NullPointerException ... OK great. Now there will be a stack trace on stdout or stderr, which tells you which line it is. Perhaps you could post the code around that line for us ... rather than posting reams of code and expecting us to compile it up and run it for you.

BTW, please post your code between the tags [ignore]
Code:
[/ignore]

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Sorry about that sedj. Here is all the errors that I am getting.

java.lang.NullPointerException
at mortgageCalculator.constructMortgageSelection(mortgageCalculator.java:425)
at mortgageCalculator.<init>(mortgageCalculator.java:77)
at mortgageCalculator.main(mortgageCalculator.java:54)
Exception in thread "main"

line 77:
Code:
constructMortgageSelection();

line 54:
Code:
   mortgageCalculator application = new mortgageCalculator();

line 425:
Code:
defaultOptions[i] = new JRadioButton(mortgagelist[i].toString(), false);

This errors is driving me crazy, I just can't seem to figure out why is compiles and it then it won't just run.

 
Your array mortgagelist [] isn't initialized,

Code:
mortgagelist = new Mortgage [17];

and must be filled, before you access its elements:
Code:
mortgagelist[0] = new Mortgage (foo, bar);
mortgagelist[1] = new Mortgage (1, foobar);
mortgagelist[2] = new Mortgage (2, bar);
mortgagelist[3] = new Mortgage (3, foo);

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top