Results 1 to 5 of 5
- 12-15-2008, 01:15 PM #1
Member
- Join Date
- Dec 2008
- Posts
- 10
- Rep Power
- 0
The addition program is providing incorrect sum '0'
import javax.swing.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Addition extends JFrame implements ActionListener
{
int num1, num2, total;
JButton b=new JButton("Submit");
JButton exit=new JButton("Exit");
JButton clr=new JButton("Clear");
JTextField t1=new JTextField(10);
JTextField t2=new JTextField(10);
JTextField tsum=new JTextField(10);
JLabel l1= new JLabel("Number 1");
JLabel l2= new JLabel("Number 2");
JLabel sum=new JLabel("Sum");
public Addition()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
c.add(l1);
c.add(t1);
c.add(l2);
c.add(t2);
c.add(sum);
c.add(tsum);
c.add(b);
c.add(exit);
c.add(clr);
exit.addActionListener(this);
b.addActionListener(this);
clr.addActionListener(this);
try
{
num1=Integer.parseInt(t1.getText());
num2=Integer.parseInt(t2.getText());
total=num1+num2;
}
catch (NumberFormatException e)
{
Toolkit.getDefaultToolkit().beep();
}
setSize(200,200);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if("Submit".equals(str))
{
tsum.setText(""+total);
}
if("Clear".equals(str))
{
t1.setText("");
t2.setText("");
tsum.setText("");
}
if("Exit".equals(str))
{
System.exit(0);
}
}
public static void main(String args[])
{
Addition add=new Addition();
}
}
- 12-15-2008, 01:56 PM #2
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 7
You need to figure the total in the action performed method. Currently, you are summing the values present in the textfields before the GUI is ever shown, which are then blank, which then produces a 0 sum.
- 12-16-2008, 09:57 AM #3
Member
- Join Date
- Dec 2008
- Posts
- 10
- Rep Power
- 0
Can you help me rewriting the entire program properly, so that it works fine?
- 12-16-2008, 10:16 AM #4
Senior Member
- Join Date
- Jun 2008
- Posts
- 2,366
- Rep Power
- 7
Noone said you needed to completely rewrite it.
Simply move the try/catch block into the actionPerformed method, directly before the first call to setText.
- 12-16-2008, 01:43 PM #5
Member
- Join Date
- Dec 2008
- Posts
- 10
- Rep Power
- 0
Similar Threads
-
Incorrect Package? Help!
By chaits86 in forum NetBeansReplies: 10Last Post: 12-17-2008, 03:08 AM -
Addition java program
By tabrez_k81 in forum New To JavaReplies: 5Last Post: 12-15-2008, 10:08 AM -
Dubugger points to incorrect source code
By gdias in forum EclipseReplies: 0Last Post: 09-02-2008, 08:07 PM -
Simple Addition Program Outputting Wrong Value
By carlodelmundo in forum New To JavaReplies: 4Last Post: 08-05-2008, 03:37 AM -
Addition program that displays the sum of two numbers
By Java Tip in forum Java TipReplies: 0Last Post: 03-28-2008, 08:46 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks