Here is what I need to do: have three editable text fields labelled operand1, operator, and operand2, and a fourth read-only text field labelled result. Have a button labelled Calculate. WHen the button is clicked the appropriate operator is applied to the two operands and the resulting value placed in the result text field. If the operator is invalid, send a message to System.err<.code>
Here is my code
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class calculator extends Applet implements ActionListener {
public void init() {
Label lbOp1 = new Label("operand1");
op1 = new TextField("0");
calculate = new Button("=");
calculate.addActionListener(this);
clearEm = new Button("Clear");
clearEm.addActionListener(this);
Label lbOper = new Label("operator");
oper = new TextField("+");
Label lbOp2 = new Label("operand2");
op2 = new TextField("0");
Label lbResult = new Label("result");
add(lbOp1);
add(op1);
add(lbOper);
add(oper);
add(lbOp2);
add(op2);
add(lbResult);
add(result);
add(calculate);
add(clearEm);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==calculate)
{
one = op1.getText();
two = op2.getText();
num1 = Integer.parseInt(one);
num2 = Integer.parseInt(two);
strOper = oper.getText();
if(strOper.equals("+"))
{
answer = num1 + num2;
math = Integer.toString(answer);
result.setText(math);
}
else if(strOper.equals("-"))
{
answer = num1 - num2;
math = Integer.toString(answer);
result.setText(math);
}
else if(strOper.equals("*"))
{
answer = num1 * num2;
math = Integer.toString(answer);
result.setText(math);
}
else if(strOper.equals("/"))
{
answer = num1 / num2;
math = Integer.toString(answer);
result.setText(math);
}
else
System.err.println("invalid operator");
}
if(e.getSource()==clearEm)
{
op1.setText("");
op2.setText("");
oper.setText("");
}
}
TextField op1, op2, oper, result;
Button calculate, clearEm;
String one, two, strOper, math;
int num1, num2, answer;
}
The app won't show and the console shows this error
java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at calculator.init(calculator.java:33)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception: java.lang.NullPointerException