The following code is for a standalone applet that calculates a shipping rate based on a selected shipping method. Normally, the program would read the total price of purchases from the website but for the sake of this exercise, the user will enter the price on the applet.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.text.DecimalFormat;

public class CandleLineApplet extends Applet implements ItemListener
{
	//declare variables and construct a color
	double orderAmount, rate;
	int rateCode;


	//create components for applet
	Label companyNameLabel = new Label("CandleLine -- Candles Online");
	Label promptLabel = new Label("Please enter the total dollar amount of your order");
	TextField salesField = new TextField(20);
	Label shippingMethodLabel = new Label("Please choose your method of shipping:");

	CheckboxGroup rateGroup = new CheckboxGroup();
	Checkbox priorityBox = new Checkbox("Priority (Overnight)", false, rateGroup);
	Checkbox expressBox = new Checkbox("Express (2 business days)", false, rateGroup);
	Checkbox standardBox = new Checkbox("Standard (3 to 7 business days)", false, rateGroup);
	Checkbox hiddenBox = new Checkbox("", false, rateGroup);

	Label sloganLabel = new Label("We guarantee on time delivery, or your money back");
	Label outputLabel;

	public void init()
	{
		setBackground(Color.green);
		setForeground(Color.black);
		add(companyNameLabel);
		add(promptLabel);
		add(salesField);
		salesField.requestFocus();
		salesField.setForeground(Color.black);
		add(shippingMethodLabel);
		add(priorityBox);
		priorityBox.addItemListener(this);
		add(expressBox);
		expressBox.addItemListener(this);
		add(standardBox);
		standardBox.addItemListener(this);
		add(sloganLabel);

	}

	public void itemStateChanged(ItemEvent rateChoice)
	{
		try
			{
				orderAmount = getOrderAmount();
				rateCode = getRateCode();
				rate = calculateRate(rateCode, orderAmount);
				displayResult(orderAmount, rate);
			}
		catch (NumberFormatException e)
			{
				outputLabel.setText("You must enter a dollar amount greater than zero.");
				hiddenBox.setState(true);
				salesField.setText("");
				salesField.requestFocus();
			}
	}

	public double getOrderAmount()
	{
		double order = Double.parseDouble(salesField.getText());
		if (order <= 0.00) throw new NumberFormatException();
		return order;
	}

	public int getRateCode()
	{
		int code = 0;

		if (priorityBox.getState()) code = 1;
			else
				if (expressBox.getState()) code = 2;
				else
					if (standardBox.getState()) code = 3;
		return code;
	}

	public double calculateRate(int rateCode, double totalOrderCost )
	{
		double shippingRate = 0.00;

		switch (rateCode)
		{
			case 1:
				shippingRate = 16.95;
				break;

			case 2:
				shippingRate = 13.95;
				break;

			case 3:
				if (totalOrderCost < 100.00)
					shippingRate = 7.95;
				break;

		}

		return shippingRate;
	}

	public void displayResult(double orderTotal, double shippingRate )
	{
		DecimalFormat twoDigits = new DecimalFormat("$#,000.00");
		outputLabel.setText("Your shipping charge for your order of " + twoDigits.format(orderTotal) + " is " + twoDigits.format(shippingRate));
	}


}

The problem here is that this application is throwing a NullPointerException when itemStateChanged() is invoked - been struggling for a week now to debug it but had no success.

This is the error message that was generated at runtime:

Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
at CandleLineApplet.itemStateChanged(CandleLineApplet.java:67)
at java.awt.Checkbox.processItemEvent(Checkbox.java:559)
at java.awt.Checkbox.processEvent(Checkbox.java:526)
at java.awt.Component.dispatchEventImpl(Component.java:3955)
at java.awt.Component.dispatchEvent(Component.java:3803)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
read.java:234)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)


PS; If this can be coded any simpler, I would really appreciate any suggestions.

Thanks

Edited 5 Years Ago by Ezzaral: Updated code tag to show Java syntax.

at CandleLineApplet.itemStateChanged(CandleLineApplet.java:67)

Line 67 is part of public double getOrderAmount() in your code, so the code you posted doesn't match the error message. This is not helpful!

Null pointer means uninitialised variable OR a method returned null and you tried to use the returned value. Check the actual line in the code version corresponding to the error message to see which it is.

Line 67 is part of public double getOrderAmount() in your code, so the code you posted doesn't match the error message. This is not helpful!

The code that I posted as well as the error message, was on a first run of the code so I don't understand how it could be mismatched.

Null pointer means uninitialised variable OR a method returned null and you tried to use the returned value. Check the actual line in the code version corresponding to the error message to see which it is.

I suspect that

double order = Double.parseDouble(salesField.getText());

is either not working or doesn't work when the value is 0.00 and that could be why it's returning a NullPointerException. The application is failing from this point onward because it has to use this value for all subsequent operations. Is there anyway that I can watch that variable while running the code?

I don't know either, but the line number in the message does not correspond to the line numbers in the code you posted. Nevermind.
Read Ezzaral's post again, he is wize. My guess is that the error message actually refers to line 59 in the code as posted.
Watch var while running.. if you are using a Java IDE like Eclipse or NEtBeans that var monitoring and breakpoints are all there for you to use (although its a bit of a learning curve). Otherwize simply add some print statements to see what's happening,, eg

System.out.println("SalesField text = " + salesField.getText());
double order = Double.parseDouble(salesField.getText()); 
System.out.println("order value = " + order);

Thank you James.

I'm using a simple text editor; it doesn't have the functionality of a Java IDE like Eclipse or NetBeans. Will try over the weekend to download a proper Java IDE.

I'm at work now and work has its own development challenges.

I don't know your experience level, but many people would advise staying with a simple text editor to build real Java skills before getting dependent on the assistance of a full IDE. Personally I'm not convinced, but hey, each man his own opinion.

To avoid big confusion with profesional IDE, I can recommend to try out JCreator. Very simple Windows IDE for java, more of text editor with syntax highlight. Simple to use, you do not need to try create project with it, just create files in folder, compile and run

I don't know your experience level, but many people would advise staying with a simple text editor to build real Java skills before getting dependent on the assistance of a full IDE. Personally I'm not convinced, but hey, each man his own opinion.

Work-wise I'm new to development - have been doing software testing for the past 6 years. On an academic level, I've been using text editors for the past 3 years. Text editors are good for learning Java principles but IDE's are so much better when you want to code more efficiently. Also, I could do with the assistance of an IDE, especially with the debugging and code-completion features.

To avoid big confusion with profesional IDE, I can recommend to try out JCreator. Very simple Windows IDE for java, more of text editor with syntax highlight. Simple to use, you do not need to try create project with it, just create files in folder, compile and run

Thanks. I will try this too . . . for home use at least. We're using Eclipse and NetBeans at work so I might as well familiarise myself with the use of it.

Thanks. I will try this too . . . for home use at least. We're using Eclipse and NetBeans at work so I might as well familiarise myself with the use of it.

If you already familiar with Eclipse or NetBeans then by no means go for them. I suggested JCreator just because you said you use text editor

If you already familiar with Eclipse or NetBeans then by no means go for them. I suggested JCreator just because you said you use text editor

I'm not really all that familiar with Eclipse and NetBeans - still on a steep learning curve at work.

I appreciate your suggestion of JCreator because it would just be way much better for honing my Java development skills on an academic level. Also, colleges and universities seems to prefer or even recommend the use of text editors for development because how else is someone going to learn the basics - IDE's with code-completion just wouldn't be good for that.

This happens all the time...

Just because you have defined a Label, it doesn't create it.
You have to create your Label BEFORE you can use it.
When I want to use a Label (or JLabel) I always create it at the time of defining it.

JLabel MyLabel = new JLabel ("My Label String");

You could, if you wish, create it after defining it.

JLabel MyLabel;
MyLabel = new JLabel ("My Label String");

This happens all the time...

Just because you have defined a Label, it doesn't create it.
You have to create your Label BEFORE you can use it.
When I want to use a Label (or JLabel) I always create it at the time of defining it.

JLabel MyLabel = new JLabel ("My Label String");

You could, if you wish, create it after defining it.

JLabel MyLabel;
MyLabel = new JLabel ("My Label String");

This was indeed the problem.

I just created the label at the same time as defining it and the exception error was gone.

Thanks for all the help.

Yes, I tried to guide you towards that conclusion in the very first post 6 days ago.

Edited 5 Years Ago by Ezzaral: n/a

Yes, I tried to guide you towards that conclusion in the very first post 6 days ago.

My apologies then. It was not that I was ignoring your advice; I tend to look to deep and looked past the glaringly obvious.

This question has already been answered. Start a new discussion instead.