CS 202 - Computer Science II - Fall 2005
try and catch


Loyola College > Department of Computer Science > Dr. James Glenn > CS 202 > Examples and Lecture Notes > try and catch

Calculator.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Calculator extends JApplet
{
	private JTextField input, output;

	public void init()
	{
		getContentPane().setLayout(new GridLayout(3, 1));
		
		input = new JTextField();
		getContentPane().add(input);
		
		output = new JTextField();
		output.setEditable(false);
		getContentPane().add(output);
		
		JButton calcButton = new JButton("Calculate");
		getContentPane().add(calcButton);
		calcButton.addActionListener(new ButtonListener());
	}
	
	private class ButtonListener implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			double in = 0.0;
		
			try
			{
				in = Double.parseDouble(input.getText());
				double out = Math.sqrt(in);
			
				output.setText("" + out);
			}
			catch (NumberFormatException ex)
			{
				output.setText("Please enter a numeric value");
			}
			
				}
	}
}
		
		
This code can also be downloaded from the file Calculator.java.