Button counter not upating - java

Trying to write a simple program to display a telephone number typed in with the buttons. I have a counter set up for each time a button is pushed to automatically insert the "-" after the 3rd and 6th number input. My counter doesn't seem to be updating on the button pushes. I can't see why. It's probably quite simple but I would greatly appreciate any help.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BorderPanel extends JPanel
{
//variables
int counter = 0;
int total;
Object source = new Object();
String display = "";
String s;
//buttons
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b0 = new JButton("0");
JButton bstar = new JButton("*");
JButton blb = new JButton("#");
JButton resetB = new JButton("RESET");
//layout managers
BorderLayout layoutB = new BorderLayout();
GridLayout layoutG = new GridLayout(4,3);
//panels
JPanel bigP = new JPanel(layoutB);
JPanel numberP = new JPanel(layoutG);
//JLabel
JLabel displayL = new JLabel();
JLabel counterL = new JLabel();
//listener
ButtonListener buttonListener = new ButtonListener();
public BorderPanel()
{
/****************START**********************/
displayL.setText(display);
numberP.add(b1);
b1.addActionListener(buttonListener);
numberP.add(b2);
b2.addActionListener(buttonListener);
numberP.add(b3);
b3.addActionListener(buttonListener);
numberP.add(b4);
b4.addActionListener(buttonListener);
numberP.add(b5);
b5.addActionListener(buttonListener);
numberP.add(b6);
b6.addActionListener(buttonListener);
numberP.add(b7);
b7.addActionListener(buttonListener);
numberP.add(b8);
b8.addActionListener(buttonListener);
numberP.add(b9);
b9.addActionListener(buttonListener);
numberP.add(bstar);
bstar.addActionListener(buttonListener);
numberP.add(b0);
b0.addActionListener(buttonListener);
numberP.add(blb);
blb.addActionListener(buttonListener);
resetB.addActionListener(buttonListener);
bigP.add(displayL, layoutB.SOUTH);
bigP.add(resetB, layoutB.EAST);
bigP.add(numberP, layoutB.CENTER);
add(counterL);
add(bigP);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
counter ++;
if (total == 3)
display += "-";
if (total == 6)
display += "-";
source = event.getSource();
if (source == b1)
display += "1";
if (source == b2)
display += "2";
if (source == b3)
display += "3";
if (source == b4)
display += "4";
if (source == b5)
display += "5";
if (source == b6)
display += "6";
if (source == b7)
display += "7";
if (source == b8)
display += "8";
if (source == b9)
display += "9";
if (source == b0)
display += "0";
if (source == bstar)
display += "*";
if (source == blb)
display += "#";
if (source == resetB)
display = "";
counter = 0;
displayL.setText(display);
counterL.setText("" + counter);
}
}
}

You need to include braces for this if statement otherwise the counter = 0 is always executed. If you don't use braces for a control structure, it only includes the very next statement in the scope of the structure.
So your code
if (source == resetB)
display = "";
counter = 0;
is actually equivalent to
if (source == resetB)
{
display = "";
}
counter = 0;
You need to enclose both statements in braces. This is why you should get in the habit of using braces for control structures (if/else/for/while etc) unless you're sure it won't cause any confusion whatsoever. Even then, you risk something like this happening.
if (source == resetB)
{
display = "";
counter = 0;
}
Also, you are setting total but never using it, so although it will add to counter it won't display the hyphens.
You need to change both usages of total to counter and move it after the number is added to the display, otherwise you will get 00-000-00000 instead of 000-000-0000
So it will look like:
if (source == b1)
display += "1";
//...etc
if (source == blb)
display += "#";
if (source == resetB)
{
display = "";
counter = 0;
}
if (counter == 3)
display += "-";
if (counter == 6)
display += "-";

Related

Swing - Try to make simple calculator display error when dividing by zero

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JCalculator implements ActionListener {
private JButton[] buttons;
private JLabel display;
//Put button shapes in an array
private String[] button_Shapes = {"7", "8", "9", "/", "4", "5", "6", "x", "1",
"2", "3", "-", "0", "C", "=", "+"};
private int operand1, operand2, result;
private String operator;
//Create new form Calculator
public JCalculator(){
//Create new JFrame container
JFrame jfrm = new JFrame("Calculator");
//Set the initial size for frame
jfrm.setSize(500,500);
//Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set the calculator to center on the screen
jfrm.setLocationRelativeTo(null);
//Set the icon
ImageIcon icon = new ImageIcon("C:/Users/zetsu/Desktop/JCalculator.png");
jfrm.setIconImage(icon.getImage());
//Create label
display = new JLabel("0", JLabel.RIGHT);
//Put border around display label
display.setBorder(BorderFactory.createLineBorder(Color.black));
//Create a grid layout
GridLayout layout = new GridLayout(4,4);
//Create a panel and set layout
JPanel bottom_Panel = new JPanel();
bottom_Panel.setLayout(layout);
//Create an array of buttons
buttons = new JButton[16];
for(int i = 0; i < button_Shapes.length; i++){
//make new button name
JButton btn = new JButton("" + button_Shapes[i]);
buttons[i] = btn;
//add action listener for each button
btn.addActionListener(this);
//add each button to panel
bottom_Panel.add(btn);
}
//Set [=] button to default
jfrm.getRootPane().setDefaultButton(buttons[14]);
//Set Mnemonic to Alt+[C]
buttons[13].setMnemonic(KeyEvent.VK_C);
//Add label to content pane
jfrm.add(display, BorderLayout.NORTH);
//Add panel to content pane
jfrm.add(bottom_Panel, BorderLayout.CENTER);
jfrm.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton)e.getSource();
if(display.getText().equals("0")
|| display.getText().equals(button_Shapes[3])
|| display.getText().equals(button_Shapes[7])
|| display.getText().equals(button_Shapes[11])
|| display.getText().equals(button_Shapes[15])){
display.setText("");
}
if(btn == buttons[0] || btn == buttons[1] || btn == buttons[2]
|| btn == buttons[4] || btn == buttons[5] || btn == buttons[6]
|| btn == buttons[8] || btn == buttons[9] || btn == buttons[10]
|| btn == buttons[12]){
display.setText("" + display.getText()+ btn.getText());
if(display.getText().length() > 7){
buttons[0].setEnabled(false);
buttons[1].setEnabled(false);
buttons[2].setEnabled(false);
buttons[4].setEnabled(false);
buttons[5].setEnabled(false);
buttons[6].setEnabled(false);
buttons[8].setEnabled(false);
buttons[9].setEnabled(false);
buttons[10].setEnabled(false);
buttons[12].setEnabled(false);
}
}
if(btn == buttons[3] || btn == buttons[7] || btn == buttons[11]
|| btn == buttons[15]){
buttons[0].setEnabled(true);
buttons[1].setEnabled(true);
buttons[2].setEnabled(true);
buttons[4].setEnabled(true);
buttons[5].setEnabled(true);
buttons[6].setEnabled(true);
buttons[8].setEnabled(true);
buttons[9].setEnabled(true);
buttons[10].setEnabled(true);
buttons[12].setEnabled(true);
operand1 = Integer.parseInt(display.getText());
operator = btn.getText();
display.setText("" + operator);
}
if(btn == buttons[14]){
buttons[0].setEnabled(true);
buttons[1].setEnabled(true);
buttons[2].setEnabled(true);
buttons[4].setEnabled(true);
buttons[5].setEnabled(true);
buttons[6].setEnabled(true);
buttons[8].setEnabled(true);
buttons[9].setEnabled(true);
buttons[10].setEnabled(true);
buttons[12].setEnabled(true);
operand2 = Integer.parseInt(display.getText());
if(operator.equals(button_Shapes[3])){
if(operand2 == 0){
display.setText("Div by 0");
}
else{
result = operand1 / operand2;
}
}
else if(operator.equals(button_Shapes[7])){
result = operand1 * operand2;
}
else if(operator.equals(button_Shapes[11])){
result = operand1 - operand2;
}
else if(operator.equals(button_Shapes[15])){
result = operand1 + operand2;
}
if(String.valueOf(result).length() > 8){
display.setText("Overflow");
}
else{
display.setText(String.valueOf(result));
}
}
if(btn == buttons[13]){
buttons[0].setEnabled(true);
buttons[1].setEnabled(true);
buttons[2].setEnabled(true);
buttons[4].setEnabled(true);
buttons[5].setEnabled(true);
buttons[6].setEnabled(true);
buttons[8].setEnabled(true);
buttons[9].setEnabled(true);
buttons[10].setEnabled(true);
buttons[12].setEnabled(true);
display.setText("0");
}
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new JCalculator();
}
});
}
}
I am trying to write a program to create a swing gui of a simple calculator. Initially, the calculator will display a zero. All the operations are in the form:
(operand1 operator1 operand2 =) operator2 operand3 =
When operand1 is entered, the initial zero disappears and operand1 shows up on the display. When operator1 is pressed, the number on the screen disappears and the operator shows up. When operator2 is entered, the operator disappears and operator2 shows up on screen. When the equal sign is pressed, the result of the operation would be display on the screen. What I am trying to do is display an error "Div by 0" whenever a number divides by zero. However, whenever I divide, add, subtract, or multiply by zero I keep getting the error NumberFormatException. I think the problem is in this if statement:
if(display.getText().equals("0")
|| display.getText().equals(button_Shapes[3])
|| display.getText().equals(button_Shapes[7])
|| display.getText().equals(button_Shapes[11])
|| display.getText().equals(button_Shapes[15])){
display.setText("");
}
The purpose of this if is to erase the zero on the display whenever the first number is pressed or when an operator is pressed. What I think can solve this problem is somehow notify the if statement that operand2 has the value of zero so it doesn't set the text to (""). I don't know how to do that. Please help.
You need to rethink this entire application. But maybe you should try something like this to actually find out if you're dividing by zero:
try
{
//do calculation
} catch (ArithmeticException ae)
{
if (ae.getMessage().equalsIgnoreCase("/ by zero"))
{
//do something
}
}

Trying to make a functional calculator in java, I can't figure out where I'm going wrong [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'd like to start off saying that I'm still really new to java, but I promise this is not a troll post. So I have to make a functional four function calculator for school. It's really basic but for some reason I can't get it to work properly. I was given the following as example code, my teacher told us to infer the rest.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator implements ActionListener
{
JFrame f1;
JTextField display;
JButton b1,b2,addb,equalsb,clearb;
JPanel p1;
String value,operation;
double secondnum, total;
public Calculator()
{
value = "";
total = 0.0;
secondnum = 0.0;
f1 = new JFrame("Calculator");
f1.setSize(400,100);
Container c1 = f1.getContentPane();
display = new JTextField(15);
b1 = new JButton("1");
b1.addActionListener(this); // adds a Listener for Button b1
b2 = new JButton("2");
b2.addActionListener(this);
addb = new JButton("+");
addb.addActionListener(this);
equalsb = new JButton("=");
equalsb.addActionListener(this);
clearb = new JButton("C");
clearb.addActionListener(this);
p1 = new JPanel();
p1.add(display);
p1.add(b1);
p1.add(b2);
p1.add(addb);
p1.add(equalsb);
p1.add(clearb);
c1.add(p1);
f1.show();
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource()== b1)
value = value + "1";
if (event.getSource() == b2)
value = value + "2";
if (event.getSource() == clearb)
{
total = 0.0;
secondnum = 0.0;
value = "";
}
if (event.getSource() == addb)
{
total = Double.parseDouble(value);
operation = "add";
value = "";
}
if (event.getSource() == equalsb)
{
secondnum = Double.parseDouble(value);
if(operation.equals("add"))
total = total + secondnum;
value = ""+ total; //value becomes what the total is to be diplays
}
display.setText(value);
}
}
This works, so from it I created the following. I'm pretty sure i'm going wrong in the function keys, but I have no clue where I messed up.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calculator implements ActionListener
{
JFrame f;
Container c;
JPanel p;
JTextField display;
JButton b1, b2, b3, bdiv, b5, b6, b7, bmult, b9, b10, b11, badd, b13, bdecimal, bequals, bsub, bclear;
String value, operation;
double secondnum, total;
public Calculator()
{
value = "";
total = 0.0;
secondnum = 0.0;
f = new JFrame("Calculator");
f.setSize(333,225);
c = f.getContentPane();
p = new JPanel();
display = new JTextField(20);
b1 = new JButton("7");
b1.addActionListener(this);
b2 = new JButton("8");
b2.addActionListener(this);
b3 = new JButton("9");
b3.addActionListener(this);
bdiv = new JButton("/");
bdiv.addActionListener(this);
b5 = new JButton("4");
b5.addActionListener(this);
b6 = new JButton("5");
b6.addActionListener(this);
b7 = new JButton("6");
b7.addActionListener(this);
bmult = new JButton("x");
bmult.addActionListener(this);
b9 = new JButton("1");
b9.addActionListener(this);
b10 = new JButton("2");
b10.addActionListener(this);
b11 = new JButton("3");
b11.addActionListener(this);
badd = new JButton("+");
badd.addActionListener(this);
b13 = new JButton("0");
b13.addActionListener(this);
bdecimal = new JButton(".");
bdecimal.addActionListener(this);
bequals = new JButton("=");
bequals.addActionListener(this);
bsub = new JButton("-");
bsub.addActionListener(this);
bclear = new JButton("C");
bclear.addActionListener(this);
p.setBackground(Color.green);
p.add(display);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bdiv);
p.add(b5);
p.add(b6);
p.add(b7);
p.add(bmult);
p.add(b9);
p.add(b10);
p.add(b11);
p.add(badd);
p.add(b13);
p.add(bdecimal);
p.add(bequals);
p.add(bsub);
p.add(bclear);
c.add(p);
f.show();
}
public void actionPerformed (ActionEvent event)
{
if(event.getSource() == b1)
{
value = value + "7";
}
if(event.getSource() == b2)
{
value = value + "8";
}
if(event.getSource() == b3)
{
value = value + "9";
}
if(event.getSource() == b5)
{
value = value + "4";
}
if(event.getSource() == b6)
{
value = value + "5";
}
if(event.getSource() == b7)
{
value = value + "6";
}
if(event.getSource() == b9)
{
value = value + "1";
}
if(event.getSource() == b10)
{
value = value + "2";
}
if(event.getSource() == b11)
{
value = value + "3";
}
if(event.getSource() == b13)
{
value = value + "0";
}
if(event.getSource() == bdecimal)
{
value = value + ".";
}
if(event.getSource() == badd)
{
total = Double.parseDouble(value);
operation = "add";
value = "";
}
if(event.getSource() == bmult)
{
total = Double.parseDouble(value);
operation = "multiply";
value = "";
}
if(event.getSource() == bsub)
{
total = Double.parseDouble(value);
operation = "subtract";
value = "";
}
if(event.getSource() == bdiv)
{
total = Double.parseDouble(value);
operation = "divide";
value = "";
}
if(event.getSource() == bclear)
{
total = 0.0;
secondnum = 0.0;
value = "";
}
if(event.getSource() == bequals)
{
secondnum = Double.parseDouble(value);
{
if(operation.equals("add));
total = total + secondnum;
}
{
if(operation.equals("subtract"));
total = total - secondnum;
}
if(operation.equals("divide"));
total = total / secondnum;
{
if(operation.equals("multiply"));
total = total * secondnum;
}
value = "" + tottal
}
display.setText(value);
}
}
Any help is much appreciated, I realize it's probably just a stupid mistake.
You have strange conditions on the end of the source code:
if(operation.equals("multiply"));
total = total * secondnum;
this won't multiply because of semicolon on the end of if
this is better:
if(operation.equals("multiply"))
total = total * secondnum;
And I cant understand your block of codes here, if you want to make if do this:
if(condition){
command1;
command2;
}
and not:
{
if(condition)
command1;
command2;
}

Why is my ItemListener program not allowing me to select an option from two different JComboBoxes in Java?

My program will only do one JcomboBox at a time when I am trying to get both numbers to be added together to display the final number.
It allows me to run the program, but it will not display the final price because it does not want to select two things at once.
Here is the code for my program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CottageRental2 extends JFrame implements ItemListener{
// Declare all instance data (primitives and objects used)
private int WIDTH = 676;
private int HEIGHT = 321;
Container con;
private JLabel label1;
private JLabel label2;
private JLabel label3;
JComboBox cbox1;
JComboBox cbox2;
String [ ] roomChoice = {"1 Bedroom: $600","2 Bedroom: $800","3 Bedroom: $1000"};
String [ ] activityChoice = {"Horse Back Riding: $60","Rafting: $40","Row Boat Rental: $50"};
ImageIcon icon1 = new ImageIcon("C:\\Users\\Coding\\Desktop\\cottage.jpeg");
Font f1 = new Font("Ariel", Font.BOLD, 30);
//constructor
public CottageRental2(){
super("Cottage Rental");
con = getContentPane();
con.setLayout(new BorderLayout());
con.setBackground(Color.GRAY);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void createGUI(){
label1 = new JLabel("Woodberry Cottage Rental", JLabel.CENTER);
label1.setFont(f1);
label1.setForeground(Color.WHITE);
label2 = new JLabel("Rental Amount Due: $660", JLabel.CENTER);
label2.setFont(f1);
label2.setForeground(Color.WHITE);
label3 = new JLabel(icon1);
cbox1 = new JComboBox();
cbox1.addItem(roomChoice[0]);
cbox1.addItem(roomChoice[1]);
cbox1.addItem(roomChoice[2]);
cbox1.addItemListener(this);
cbox2 = new JComboBox();
cbox2.addItem(activityChoice[0]);
cbox2.addItem(activityChoice[1]);
cbox2.addItem(activityChoice[2]);
cbox2.addItemListener(this);
con.add(label1, BorderLayout.NORTH);
con.add(label2, BorderLayout.SOUTH);
con.add(label3, BorderLayout.CENTER);
con.add(cbox1, BorderLayout.WEST);
con.add(cbox2, BorderLayout.EAST);
}
public void itemStateChanged(ItemEvent event){
Object source = event.getSource();
int price1 = 0;
int price2 = 0;
if(source == cbox1){
int roomIndex = cbox1.getSelectedIndex();
if(roomIndex == 0){
price1 = 600;
}
if(roomIndex == 1){
price1 = 800;
}
if(roomIndex == 2){
price1 = 1000;
}
}
if(source == cbox2){
int activityIndex = cbox2.getSelectedIndex();
if(activityIndex == 0){
price2 = 60;
}
if(activityIndex == 1){
price2 = 40;
}
if(activityIndex == 2){
price2 = 50;
}
}
label2.setText("Rental Amount Due: $" + (price1 + price2));
}
public static void main(String[] args){
CottageRental2 object = new CottageRental2();
object.createGUI();
object.setSize(675, 320);
}
}
Your problem is your if (source == ...) if blocks which prevent the program from getting the selected item from the other JComboBox, the one that isn't being actively selected.
One solution: get rid of the offending if blocks that test for the source of the event in the listener:
public void itemStateChanged(ItemEvent event) {
// Object source = event.getSource();
int price1 = 0;
int price2 = 0;
// if(source == cbox1){
int roomIndex = cbox1.getSelectedIndex();
if (roomIndex == 0) {
price1 = 600;
} else if (roomIndex == 1) {
price1 = 800;
} else if (roomIndex == 2) {
price1 = 1000;
}
// }
// if(source == cbox2){
int activityIndex = cbox2.getSelectedIndex();
if (activityIndex == 0) {
price2 = 60;
} else if (activityIndex == 1) {
price2 = 40;
} else if (activityIndex == 2) {
price2 = 50;
}
// }
label2.setText("Rental Amount Due: $" + (price1 + price2));
}
Also, it would be safer if you use some else if blocks in your item selection statements.

Java Calculator Assistance

This is my 1st post here and I am hoping if I could get some help on a school project I have. The project is to make a calculator in Java and I have made it and it works fine for the most part, only problem I am having is that when I get an answer - lets say 5+5=10 and 10 is displayed, when I want to enter another number lets say I want to enter in 8*10 and in order to do that I write in 8, instead of deleting the previous answer which is 10 and write 8 instead of that number it will write 8 after 10, so it will be 108. What I want is for the previous answer to be deleted once I enter in a new number after an answer has been give. I hope I explained it good, here is my code and I would love some assistance on the matter since everything I tried hasn't worked. Thanks in advance.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator_UI implements ActionListener {
JFrame frame = new JFrame("Calculator");
JPanel panel = new JPanel();
JTextArea text = new JTextArea(1, 20);
JButton but1 = new JButton("1");
JButton but2 = new JButton("2");
JButton but3 = new JButton("3");
JButton but4 = new JButton("4");
JButton but5 = new JButton("5");
JButton but6 = new JButton("6");
JButton but7 = new JButton("7");
JButton but8 = new JButton("8");
JButton but9 = new JButton("9");
JButton but0 = new JButton("0");
JButton butadd = new JButton("+");
JButton butsub = new JButton("-");
JButton butmulti = new JButton("*");
JButton butdiv = new JButton("/");
JButton buteq = new JButton("=");
JButton butclear = new JButton("C");
Double number1, number2, result;
int addc = 0, subc = 0, multic = 0, divc = 0;
public void ui() {
frame.setVisible(true);
frame.setSize(230, 200);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel.add(text);
panel.add(but1);
panel.add(but2);
panel.add(but3);
panel.add(but4);
panel.add(but5);
panel.add(but6);
panel.add(but7);
panel.add(but8);
panel.add(but9);
panel.add(but0);
panel.add(butadd);
panel.add(butsub);
panel.add(butmulti);
panel.add(butdiv);
panel.add(buteq);
panel.add(butclear);
but1.addActionListener(this);
but1.setBackground(Color.cyan);
but2.addActionListener(this);
but2.setBackground(Color.cyan);
but3.addActionListener(this);
but3.setBackground(Color.cyan);
but4.addActionListener(this);
but4.setBackground(Color.cyan);
but5.addActionListener(this);
but5.setBackground(Color.cyan);
but6.addActionListener(this);
but6.setBackground(Color.cyan);
but7.addActionListener(this);
but7.setBackground(Color.cyan);
but8.addActionListener(this);
but8.setBackground(Color.cyan);
but9.addActionListener(this);
but9.setBackground(Color.cyan);
but0.addActionListener(this);
but0.setBackground(Color.cyan);
butadd.addActionListener(this);
butadd.setBackground(Color.cyan);
butsub.addActionListener(this);
butsub.setBackground(Color.cyan);
butmulti.addActionListener(this);
butmulti.setBackground(Color.cyan);
butdiv.addActionListener(this);
butdiv.setBackground(Color.cyan);
buteq.addActionListener(this);
buteq.setBackground(Color.cyan);
butclear.addActionListener(this);
butclear.setBackground(Color.cyan);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == butclear) {
number1 = 0.0;
number2 = 0.0;
text.setText("");
}
if (source == but1) {
text.append("1");
}
if (source == but2) {
text.append("2");
}
if (source == but3) {
text.append("3");
}
if (source == but4) {
text.append("4");
}
if (source == but5) {
text.append("5");
}
if (source == but6) {
text.append("6");
}
if (source == but7) {
text.append("7");
}
if (source == but8) {
text.append("8");
}
if (source == but9) {
text.append("9");
}
if (source == but0) {
text.append("0");
}
if (source == butadd) {
number1 = number_reader();
text.setText("");
addc = 1;
subc = 0;
multic = 0;
divc = 0;
}
if (source == butsub) {
number1 = number_reader();
text.setText("");
addc = 0;
subc = 1;
multic = 0;
divc = 0;
}
if (source == butmulti) {
number1 = number_reader();
text.setText("");
addc = 0;
subc = 0;
multic = 1;
divc = 0;
}
if (source == butdiv) {
number1 = number_reader();
text.setText("");
addc = 0;
subc = 0;
multic = 0;
divc = 1;
}
if (source == buteq) {
number2 = number_reader();
if (addc == 1) {
result = number1 + number2;
text.setText(Double.toString(result));
}
if (subc == 1) {
result = number1 - number2;
text.setText(Double.toString(result));
}
if (multic == 1) {
result = number1 * number2;
text.setText(Double.toString(result));
}
if (divc == 1) {
result = number1 / number2;
text.setText(Double.toString(result));
}
}
}
public double number_reader() {
Double num1;
String s;
s = text.getText();
num1 = Double.valueOf(s);
return num1;
}
}
When the user presses = and the result is printed, you should set a flag to true, so that the next time a number button is pressed, the result is first erased.
In fact you should even transform your whole logic into a state diagram, because if, for example, the user presses + twice, you should probably display an error message or ignore the second +, instead of reading the current number. Each state should define what happens when any button is pressed, and what the next state is depending on which button is pressed.
Since a GUI can be smarter than a real calculator, each state could also define which buttons are enabled and which ones are disabled.

Switching values in java

So basically I am learning some basic java and I am currently writing a little "game" that tells you which button to click and if you click the correct one you receive a point. The buttons are defined as b1, b2, b3, and b4. The text on them says "Button 1", "Button 2", "Button 3", and "Button 4".
What I wish to accomplish is each time I click a button, the values are reassigned randomly so that the b1 text for example might say "Button 3". But it would be random. I used Java random to get it to work how I want but now I need to solve the problem of having the buttons being assigned the same values. For example, b1 and b3 might both be named "Button 2". I'm not sure how to go about solving this problem, any help would be greatly appreciated. It is kind of frustrating me.
Ok so here is my code.... finally. Have a terrible internet connection atm.
I put comments where I need the help
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui extends JFrame implements ActionListener {
private JButton b1 = new JButton("Button 1");
private JButton b2 = new JButton("Button 2");
private JButton b3 = new JButton("Button 3");
private JButton b4 = new JButton("Button 4");
private static JLabel label = new JLabel();
private static JLabel label2 = new JLabel("You currently have 0 points.");
private JPanel p = new JPanel(new GridBagLayout());
private int points = 0;
private int randomButton;
public Gui() {
super("Button Game");
newLabel();
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.gridx = 2;
c.gridy = 1;
p.add(b1,c);
c.gridx = 1;
c.gridy = 2;
p.add(b2, c);
c.gridx = 3;
c.gridy = 2;
p.add(b3, c);
c.gridx = 2;
c.gridy = 3;
p.add(b4, c);
c.gridx = 2;
c.gridy = 2;
p.add(label, c);
c.gridx = 2;
c.gridy = 4;
p.add(label2, c);
add(p);
}
public void rearrangeButtons() {
//HERE IS WHERE I AM HAVING THE PROBLEM
//b1.setText("Button " + randomButton);
//b2.setText(newText);
//b3.setText(newText);
//b4.setText(newText);
}
public static int random(int range) {
return (int)(java.lang.Math.random() * (range+1));
}
public static void newLabel() {
switch(random(3)) {
case 0:
label.setText("Press button 1");
break;
case 1:
label.setText("Press button 2");
break;
case 2:
label.setText("Press button 3");
break;
case 3:
label.setText("Press button 4");
break;
}
}
#Override
public void actionPerformed(ActionEvent e) {
String number = label.getText();
if (e.getSource() == b1) {
if (number.endsWith("1")) {
points++;
newLabel();
} else {
points = 0;
}
}
if (e.getSource() == b2) {
if (number.endsWith("2")) {
points++;
newLabel();
} else {
points = 0;
}
}
if (e.getSource() == b3) {
if (number.endsWith("3")) {
points++;
newLabel();
} else {
points = 0;
}
}
if (e.getSource() == b4) {
if (number.endsWith("4")) {
points++;
newLabel();
} else {
points = 0;
newLabel();
}
}
rearrangeButtons();
label2.setText("You currently have " + points + " points.");
}
}
Collections gives you an easy way to do this:
Declare your button text in a List:
List<String> myList =
new ArrayList<String>(Arrays.asList("text1", "text2", "text3", "text4"));
Every time you want to change the text on the buttons, shuffle List and assign:
Collections.shuffle(myList);
b1.setText(myList.get(0));
b2.setText(myList.get(1));
b3.setText(myList.get(2));
b4.setText(myList.get(3));
Edit: Brian's way of using Shuffle is better; forgot about that method, haha. My bad. Ignore this answer and use that.
Create an ArrayList of your strings with "button 1", "button 2", "button 3", "button 4"
Every time a button is clicked, create an ArrayList that is a copy of the above array (not a copy of the reference). eg: ArrayList<String> copy = new ArrayList<String>(intialArrayList);
Then use JButton#setText and Math.Random() to choose one of those strings for the first button. Every time you choose a string, delete the string from the copy. (that would make it impossible to set a button text twice).
Then repeat with the remaining buttons, but make sure the random number generated is first between 0-3, then 0-2, then 0-1.
eg:
int j = 3;
ArrayList<String> copy = new ArrayList<String>(initialArrayList);
for(int i = 0; i< 3; i++) {
//int rand = generate random number between i and j
String text = copy.get(rand);
// setText(text) for each b1, b2, b3, b4;
// copy.remove(text);
j--;
}
Create a separate method for this so you don't have to keep typing this in for each actionPerformed method.
That's just how I would do it.
Maybe each time you want to reset the text of your buttons you build a list of the 4 texts "Button 1", "Button 2", "Button 3", "Button 4". Randomly pick one, assign it to b1, and then remove it from your list which would now have only 3 available texts left. Randomly choose again from your remaining list of 3 and assign that to b2. Continue until your list of available texts is empty (or 4 times in this case). When you need to reset these texts again just reset your list of available texts back to "Button 1", "Button 2", "Button 3", "Button 4" and repeat.

Categories

Resources