Variables not changing on action.
So i'm new to java and for one of our assignments we have to make an application that can either calculate the area of a triangle, or volume of a box. Everything in my code works but only if I change variables within the code itself, ill post the important bits and hopefully I can get some of your input.
Code Java:
public class Week05 {
boolean tri;
private void initialize() {
btnTriangle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tri = true;
lblTitle.setText("Area of Triangle");
btnTriangle.setEnabled(false);
btnBox.setEnabled(true);
lblA.setText("Enter S1");
lblB.setText("Enter S2");
lblC.setText("Enter S3");
txtA.setEditable(true);
txtB.setEditable(true);
txtC.setEditable(true);
}
});
btnTriangle.setBounds(70, 45, 89, 23);
frame.getContentPane().add(btnTriangle);
btnBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tri = false;
lblTitle.setText("Volume of a Box");
btnBox.setEnabled(false);
btnTriangle.setEnabled(true);
lblA.setText("Enter l");
lblB.setText("Enter w");
lblC.setText("Enter h");
txtA.setEditable(true);
txtB.setEditable(true);
txtC.setEditable(true);
}
JButton btnNewButton = new JButton("Calculate");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double a, b, c;
a = Double.parseDouble(txtA.getText());
b = Double.parseDouble(txtB.getText());
c = Double.parseDouble(txtC.getText());
while ( a <= 0 || b <= 0 || c <= 0){
txtOutput.setText("Values are less than 0");
return;
}
if(tri = true){
Triangle area = new Triangle( a, b, c);
txtOutput.setText("The area of the Triangle is" + area.getArea());
}
else if(tri = false) {
Box volume = new Box( a, b, c);
txtOutput.setText("The volume of the Box is" + volume.getVolume());
}
}
});
the problem I seem to be having is that my variable tri never changes to false, or if I switch boolean expressions it never changes true on the action of pressing the button for triangle or box.
Re: Variables not changing on action.
Does this even compile? I see a lot of problems that the compiler *should* complain about.
But your problem is with this statement:
Code java:
if(tri = true){...
}
else if(tri = false)...
A single-equals is an assignment, a double-equals is a comparison. So you need this instead:
Code java:
if(tri == true){...
}
else if(tri == false)...
If statements look for conditionals (binary results of either true or false), and a boolean is a conditional, so this is also acceptable:
Code java:
if(tri) {...
}
else if(!tri)...
Re: Variables not changing on action.
this was only part of the code that was giving me grief in the application. i actually saw that about a half an hour of staring at it, the == was my only problem and thanks anyways.