Reputation: 41
I am trying to make a simple calculator so that when the + button is pressed it adds two variables together but whenever the listener for the button is called, it resets the variable that I previously wanted stored. How can I get around this?
public void actionPerformed(ActionEvent e)
{
int accumulator1 = 1;
int userinput;
if(e.getSource()==input)
{
userinput = Integer.parseInt(input.getText());
System.out.println(userinput);
}
if(e.getSource()==add)
{
accumulator1 = userinput + accumulator1;
System.out.println(accumulator1);
System.out.println(userinput);
accumulator.setText(String.valueOf(accumulator1));
}
}
Upvotes: 0
Views: 33
Reputation: 916
Seems like you just need to take accumulator1 out of the function and give it a global scope. So you set it to 1 when you first declare it, and public void actionPerformed
only adds to it without declaring / reinitiating it. (Unless I'm completely misunderstanding what's going on...!)
Upvotes: 2