I am busy making a calculator but somehow the integer isn't used, I don't know why. I try to fix it but I can't find out how to do it. I use a button with a event to calculate the answer, maybe something's wrong with that. Here's my code: Btw I use Eclipse
package cal;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class cal{
//declare
JLabel l;
JButton calc = new JButton("Calculate");
JTextField f, f1;
String x, y, answer;
JTextArea a;
int answerValue, xValue, yValue;
//main
public static void main(String [] args){
cal c = new cal();
c.Start();
//Start method
}public void Start(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(640,640);
frame.setResizable(false);
//declare
l = new JLabel("enter value: ");
f = new JTextField(10);
f1 = new JTextField(10);
//remaining
JPanel p = new JPanel();
a = new JTextArea(20,50);
a.setEditable(false);
calc.addActionListener(new button());
p.add(l);
p.add(f);
p.add(f1);
p.add(calc);
p.add(a);
frame.getContentPane().add(p);
frame.setVisible(true);
}
// Calculate
class button implements ActionListener{
public void actionPerformed(ActionEvent e){
x = f.getText();
y = f1.getText();
//converting string to integer
try{
int xValue= Integer.parseInt(x);
int yValue = Integer.parseInt(y);
}catch( NumberFormatException exep){
exep.printStackTrace();
}
answerValue = xValue * yValue;
String AV =Integer.toString(answerValue);
System.out.println(answerValue);
//displaying answer
a.append(AV + "\n");
}
}
}
I am talking about the xValue and yValue
This is the problem:
try {
int xValue = Integer.parseInt(x);
int yValue = Integer.parseInt(y);
} catch (NumberFormatException exep) {
exep.printStackTrace();
}
That's declaring new local variables xValue
and yValue
, rather than changing the values of your instance variables xValue
and yValue
.
If you still want the instance variables, just change the code to avoid declaring new local variables:
try {
xValue = Integer.parseInt(x);
yValue = Integer.parseInt(y);
} catch (NumberFormatException exep) {
exep.printStackTrace();
}
Alternatively - and preferably, unless you really need them elsewhere - you could get rid of the instance variables entirely, and declare the local variables before your try/catch block:
int xValue = 0;
int yValue = 0;
try {
xValue = Integer.parseInt(x);
yValue = Integer.parseInt(y);
} catch (NumberFormatException exep) {
exep.printStackTrace();
}
Likewise you could get rid of answerValue
unless you need that elsewhere.
I'd strongly advise you to reconsider your exception "handling" strategy though. You're effectively ignoring the exception and just continuing as if everything was fine...
See more on this question at Stackoverflow