GUI Java Simple Calculator using ^ - java

I've made a simple calculator. What happens is I convert the user input to infixtopostfix and then evaluate it. Everything works fine except when the user does something like 3^2, the program doesn't convert it to post fix correctly. It should be converting it to 32^ but it's converting it to ^32. Could someone please explain to me what is wrong with my convert method that is causing this issue.
Convert method:
static String convert(String infix)
{
ArrayStack<Character> as = new ArrayStack<Character>(infix.length());
String post_expression = "";
int index = 0;
while(index < infix.length()) {
char current = infix.charAt(index);
if(current == ' ') {
index++;
continue;
}
else if(current == '(') {
as.push(current);
}
else if(current == ')') {
while(as.top() != '(') {
post_expression += as.pop();
}
as.pop();
}
else if(current == '=')
{
index++;
continue;
}
else if(current == '^')
{
post_expression += as.pop();
}
else {
while(!as.isEmpty() && as.top() > current) {
post_expression += as.pop();
}
as.push(current);
}
index++;
}
while(!as.isEmpty()) {
post_expression += as.pop();
}
return post_expression;
}
Complete Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.*;
import java.io.*;
class Calculator2 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn_add = new JButton("+");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn_sub = new JButton("-");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
JButton btn_mult = new JButton("*");
JButton btn0 = new JButton("0");
JButton btn_dot = new JButton(".");
JButton btn_del = new JButton("DEL");
JButton btn_div = new JButton("/");
JButton btn_lpr = new JButton("(");
JButton btn_rpr = new JButton(")");
JButton btn_pow = new JButton("^");
JButton btn_equ = new JButton("=");
JTextArea txt = new JTextArea();
String str_number = "";
public Calculator2() {
JFrame frame = new JFrame("Simple Java Caculator");
frame.setSize(320,420);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.setLayout(new GridLayout(2,1));
JPanel HeadPanel = new JPanel();
JPanel NumberPanel = new JPanel();
JPanel LabelPanel = new JPanel();
LabelPanel.setBackground(Color.LIGHT_GRAY);
HeadPanel.setBackground(Color.LIGHT_GRAY);
NumberPanel.setLayout(new GridLayout(5,4));
//LabelPanel.setLayout(new BorderLayout());
LabelPanel.setLayout(new GridLayout(1,1));
NumberPanel.add(btn1);
btn1.addActionListener(this);
NumberPanel.add(btn2);
btn2.addActionListener(this);
NumberPanel.add(btn3);
btn3.addActionListener(this);
NumberPanel.add(btn_add);
btn_add.addActionListener(this);
NumberPanel.add(btn4);
btn4.addActionListener(this);
NumberPanel.add(btn5);
btn5.addActionListener(this);
NumberPanel.add(btn6);
btn6.addActionListener(this);
NumberPanel.add(btn_sub);
btn_sub.addActionListener(this);
NumberPanel.add(btn7);
btn7.addActionListener(this);
NumberPanel.add(btn8);
btn8.addActionListener(this);
NumberPanel.add(btn9);
btn9.addActionListener(this);
NumberPanel.add(btn_mult);
btn_mult.addActionListener(this);
NumberPanel.add(btn0);
btn0.addActionListener(this);
NumberPanel.add(btn_dot);
btn_dot.addActionListener(this);
NumberPanel.add(btn_del);
btn_del.addActionListener(this);
NumberPanel.add(btn_div);
btn_div.addActionListener(this);
LabelPanel.add(txt);
//LabelPanel.add(btn_equ);
NumberPanel.add(btn_lpr);
btn_lpr.addActionListener(this);
NumberPanel.add(btn_rpr);
btn_rpr.addActionListener(this);
NumberPanel.add(btn_pow);
btn_pow.addActionListener(this);
NumberPanel.add(btn_equ);
btn_equ.addActionListener(this);
txt.setEditable(false);
//btn_del.setEnabled(false);
HeadPanel.add(new JLabel("A Java Calculator"));
frame.add(LabelPanel);
frame.add(NumberPanel);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn1) {
str_number+="1";
txt.setText(str_number); }
else if(e.getSource()==btn2) {
str_number+="2";
txt.setText(str_number); }
else if(e.getSource()==btn3) {
str_number+="3";
txt.setText(str_number); }
else if(e.getSource()==btn4) {
str_number+="4";
txt.setText(str_number); }
else if(e.getSource()==btn5) {
str_number+="5";
txt.setText(str_number); }
else if(e.getSource()==btn6) {
str_number+="6";
txt.setText(str_number); }
else if(e.getSource()==btn7) {
str_number+="7";
txt.setText(str_number); }
else if(e.getSource()==btn8) {
str_number+="8";
txt.setText(str_number); }
else if(e.getSource()==btn9) {
str_number+="9";
txt.setText(str_number); }
else if(e.getSource()==btn0) {
str_number+="0";
txt.setText(str_number); }
else if(e.getSource()==btn_lpr) {
str_number+="(";
txt.setText(str_number); }
else if(e.getSource()==btn_rpr) {
str_number+=")";
txt.setText(str_number); }
else if(e.getSource()==btn_pow) {
str_number+="^";
txt.setText(str_number); }
else if(e.getSource()==btn_add) {
str_number+="+";
txt.setText(str_number);}
else if(e.getSource()==btn_sub) {
str_number+="-";
txt.setText(str_number);}
else if(e.getSource()==btn_mult) {
str_number+="*";
txt.setText(str_number);}
else if(e.getSource()==btn_div) {
str_number+="/";
txt.setText(str_number);}
else if(e.getSource()==btn_equ) {
System.out.println("you clicked equal sign!");
str_number+="=";
txt.setText(str_number);
String expression = convert(str_number);
double eval = evaluate(expression);
str_number+=eval;
txt.setText(str_number);
}
else if(e.getSource()==btn_dot) {
System.out.println("you clicked dot button!");
str_number+=".";
txt.setText(str_number);
}
else if(e.getSource()==btn_del) {
System.out.println("you clicked DEL button!");
if(str_number.length() > 0)
{
str_number = str_number.substring(0, str_number.length() - 1);
}
txt.setText(str_number);
}
}
static String convert(String infix)
{
ArrayStack<Character> as = new ArrayStack<Character>(infix.length());
String post_expression = "";
int index = 0;
while(index < infix.length()) {
char current = infix.charAt(index);
if(current == ' ') {
index++;
continue;
}
else if(current == '(') {
as.push(current);
}
else if(current == ')') {
while(as.top() != '(') {
post_expression += as.pop();
}
as.pop();
}
else if(current == '=')
{
index++;
continue;
}
else if(current == '^')
{
post_expression += as.pop();
}
else {
while(!as.isEmpty() && as.top() > current) {
post_expression += as.pop();
}
as.push(current);
}
index++;
}
while(!as.isEmpty()) {
post_expression += as.pop();
}
return post_expression;
}
static double evaluate(String postfix) {
ArrayStack as = new ArrayStack(postfix.length());
char nextChar = 'm';
int index = 0;
double temp = 0.00;
while(index < postfix.length()) {
char current = postfix.charAt(index);
if(current == ' ') {
index++;
continue;
}
if(!(current == '+' || current == '-' || current == '*' || current == '/'))
{
as.push(current);
temp = (double) (current - '0');
}
else {
char a = (char) as.pop();
char b = (char) as.pop();
double c = (double) (a - '0');
double d = (double) (b - '0');
switch(current) {
case '+' :
temp = d + c;
break;
case '-' :
temp = d - c;
break;
case '*' :
temp = d * c;
break;
case '/' :
temp = d / c;
break;
case '^' :
temp = Math.pow(d, c);
break;
}
as.push(nextChar);
nextChar++;
}
index++;
}
if(as.size() == 1) {
as.pop();
}
else {
System.out.println("There is an error");
}
return temp;
}
public static void main(String[] args) {
new Calculator2();
}
}
ArrayStack code
public class ArrayStack<E> implements Stack<E> {
protected int capacity;
public static final int CAPACITY = 1000;
protected E S[];
protected int top = -1;
public ArrayStack() {
this(CAPACITY);
}
public ArrayStack(int cap) {
capacity = cap;
S = (E[]) new Object[capacity];
}
#Override
public int size() {
return top+1;
}
#Override
public boolean isEmpty() {
return (top < 0);
}
#Override
public E top() throws EmptyStackException {
if(isEmpty())
throw new EmptyStackException("Stack is empty!");
return S[top];
}
#Override
public void push(E element) {
if(size() == capacity)
throw new FullStackException("Stack is full");
S[++top] = element;
}
#Override
public E pop() throws EmptyStackException {
E element;
if(isEmpty())
throw new EmptyStackException("Stack is empty");
element = S[top];
S[top--] = null;
return element;
}
#Override
public String toString() {
String s;
s = "[";
if(size() > 0) s += S[0];
if(size() > 1)
for(int i = 1; i <= size()-1; i++) {
s += ", " + S[i];
}
return s + "]";
}
}

Related

How to sum up numbers in calculator?

When I add or minus or try to sum up any operation it dose not work. This is what I have and I believe it has something to do with the code that shows in the box
//////////
/////////
What am i doing wrong? The parent class has the buttons as an array.
public void actionPerformed(ActionEvent e) {
// Get the source of this action
JButton clickedButton = (JButton) e.getSource();
// Get the existing text from the calculator
// displayField.
String dispFieldText = parent.getDisplayValue();
dot = dispFieldText.contains(".");
if (!dispFieldText.equals(""))
enteredNumber = Double.parseDouble(dispFieldText);
if (clickedButton.getText().equals("+")) {
selectedAction = "+";
currentNumber = enteredNumber;
parent.setDisplayValue("");
} else if (clickedButton.getText().equals("-")) {
selectedAction = "-";
currentNumber = enteredNumber;
parent.setDisplayValue("");
} else if (clickedButton.getText().equals("*")) {
selectedAction = "*";
currentNumber = enteredNumber;
parent.setDisplayValue("");
} else if (clickedButton.getText().equals("/")) {
selectedAction = "/";
currentNumber = enteredNumber;
parent.setDisplayValue("");
////////////////////////////////////////////////////////////////////////////////
} else if ((clickedButton == parent.buttons[11]) && (selectedAction != null)) {
if (selectedAction.equals("+")) {
currentNumber += enteredNumber;
parent.setDisplayValue("" + currentNumber);
////////////////////////////////////////////////////////////////////////////////
} else if (selectedAction.equals("-")) {
currentNumber -= enteredNumber;
parent.setDisplayValue("" + currentNumber);
} else if (selectedAction.equals("*")) {
currentNumber *= enteredNumber;
parent.setDisplayValue("" + currentNumber);
} else if (selectedAction.equals("/")) {
currentNumber /= enteredNumber;
parent.setDisplayValue("" + currentNumber);
}
}
else {
if (!clickedButton.getText().equals("=")) {
if ((clickedButton.getText().equals(".")) && dot) {
}
else {
// Get the button label
String clickedButtonLabel = clickedButton.getText();
parent.setDisplayValue(dispFieldText + clickedButtonLabel);
}
}
}
}
}

Calculator clear result when pressing a new number

I took help to create a calculator. For example 5+3=8.0, when I press a new number after the result is shown for example 3 it will just add to the old result like this, 8.3 instead of clearing and just typing 3 by itself. If I could get some help with this I would be very thankful
I've been trying alot to fix it but I cant get it to work.
/noob programmer
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener {
JPanel[] row = new JPanel[5];
JButton[] button = new JButton[19];
String[] buttonString = {"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
".", "/", "C", "√",
"+/-", "=", "0"};
int[] dimW = {300,45,100,90};
int[] dimH = {35, 40};
Dimension displayDimension = new Dimension(dimW[0], dimH[0]);
Dimension regularDimension = new Dimension(dimW[1], dimH[1]);
Dimension rColumnDimension = new Dimension(dimW[2], dimH[1]);
Dimension zeroButDimension = new Dimension(dimW[3], dimH[1]);
boolean[] function = new boolean[4];
double[] temporary = {0, 0};
JTextArea display = new JTextArea(1,20);
Font font = new Font("Times new Roman", Font.BOLD, 14);
Calculator() {
super("Calculator");
setDesign();
setSize(380, 250);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(5,5);
setLayout(grid);
for(int i = 0; i < 4; i++)
function[i] = false;
FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);
FlowLayout f2 = new FlowLayout(FlowLayout.CENTER,1,1);
for(int i = 0; i < 5; i++)
row[i] = new JPanel();
row[0].setLayout(f1);
for(int i = 1; i < 5; i++)
row[i].setLayout(f2);
for(int i = 0; i < 19; i++) {
button[i] = new JButton();
button[i].setText(buttonString[i]);
button[i].setFont(font);
button[i].addActionListener(this);
}
display.setFont(font);
display.setEditable(false);
display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
display.setPreferredSize(displayDimension);
for(int i = 0; i < 14; i++)
button[i].setPreferredSize(regularDimension);
for(int i = 14; i < 18; i++)
button[i].setPreferredSize(rColumnDimension);
button[18].setPreferredSize(zeroButDimension);
row[0].add(display);
add(row[0]);
for(int i = 0; i < 4; i++)
row[1].add(button[i]);
row[1].add(button[14]);
add(row[1]);
for(int i = 4; i < 8; i++)
row[2].add(button[i]);
row[2].add(button[15]);
add(row[2]);
for(int i = 8; i < 12; i++)
row[3].add(button[i]);
row[3].add(button[16]);
add(row[3]);
row[4].add(button[18]);
for(int i = 12; i < 14; i++)
row[4].add(button[i]);
row[4].add(button[17]);
add(row[4]);
setVisible(true);
}
public void clear() {
try {
display.setText("");
for(int i = 0; i < 4; i++)
function[i] = false;
for(int i = 0; i < 2; i++)
temporary[i] = 0;
} catch(NullPointerException e) {
}
}
public void getSqrt() {
try {
double value = Math.sqrt(Double.parseDouble(display.getText()));
display.setText(Double.toString(value));
} catch(NumberFormatException e) {
}
}
public void getPosNeg() {
try {
double value = Double.parseDouble(display.getText());
if(value != 0) {
value = value * (-1);
display.setText(Double.toString(value));
}
else {
}
} catch(NumberFormatException e) {
}
}
public void getResult() {
double result = 0;
temporary[1] = Double.parseDouble(display.getText());
String temp0 = Double.toString(temporary[0]);
String temp1 = Double.toString(temporary[1]);
try {
if(temp0.contains("-")) {
String[] temp00 = temp0.split("-", 2);
temporary[0] = (Double.parseDouble(temp00[1]) * -1);
}
if(temp1.contains("-")) {
String[] temp11 = temp1.split("-", 2);
temporary[1] = (Double.parseDouble(temp11[1]) * -1);
}
} catch(ArrayIndexOutOfBoundsException e) {
}
try {
if(function[2] == true)
result = temporary[0] * temporary[1];
else if(function[3] == true)
result = temporary[0] / temporary[1];
else if(function[0] == true)
result = temporary[0] + temporary[1];
else if(function[1] == true)
result = temporary[0] - temporary[1];
display.setText(Double.toString(result));
for(int i = 0; i < 4; i++)
function[i] = false;
} catch(NumberFormatException e) {
}
}
public final void setDesign() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
}
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == button[0])
display.append("7");
if(ae.getSource() == button[1])
display.append("8");
if(ae.getSource() == button[2])
display.append("9");
if(ae.getSource() == button[3]) {
//add function[0]
temporary[0] = Double.parseDouble(display.getText());
function[0] = true;
display.setText("");
}
if(ae.getSource() == button[4])
display.append("4");
if(ae.getSource() == button[5])
display.append("5");
if(ae.getSource() == button[6])
display.append("6");
if(ae.getSource() == button[7]) {
//subtract function[1]
temporary[0] = Double.parseDouble(display.getText());
function[1] = true;
display.setText("");
}
if(ae.getSource() == button[8])
display.append("1");
if(ae.getSource() == button[9])
display.append("2");
if(ae.getSource() == button[10])
display.append("3");
if(ae.getSource() == button[11]) {
//multiply function[2]
temporary[0] = Double.parseDouble(display.getText());
function[2] = true;
display.setText("");
}
if(ae.getSource() == button[12])
display.append(".");
if(ae.getSource() == button[13]) {
//divide function[3]
temporary[0] = Double.parseDouble(display.getText());
function[3] = true;
display.setText("");
}
if(ae.getSource() == button[14])
clear();
if(ae.getSource() == button[15])
getSqrt();
if(ae.getSource() == button[16])
getPosNeg();
if(ae.getSource() == button[17])
getResult();
if(ae.getSource() == button[18])
display.append("0");
}
public static void main(String[] arguments) {
Calculator c = new Calculator();
}
}
So here is a working solution.
First of all your class now implements a MouseListener.
In line 7 I added the boolean value to decide whether a result was prompted or not.
private boolean resultPrompted = false;
In line 52 each button gets its own MouseListener.
button[i].addMouseListener(this);
In line 151 a result has been prompted and so we set the boolean to true
resultPrompted = true;
In the lines 234 to 240 the "magic" happens. Here you figure out whether or not a result was recently prompted. If so, we delete the current content of display. The currently typed character gets displayed alone.
Done.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener, MouseListener {
private boolean resultPrompted = false;
JPanel[] row = new JPanel[5];
JButton[] button = new JButton[19];
String[] buttonString = {"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
".", "/", "C", "√",
"+/-", "=", "0"};
int[] dimW = {300,45,100,90};
int[] dimH = {35, 40};
Dimension displayDimension = new Dimension(dimW[0], dimH[0]);
Dimension regularDimension = new Dimension(dimW[1], dimH[1]);
Dimension rColumnDimension = new Dimension(dimW[2], dimH[1]);
Dimension zeroButDimension = new Dimension(dimW[3], dimH[1]);
boolean[] function = new boolean[4];
double[] temporary = {0, 0};
JTextArea display = new JTextArea(1,20);
Font font = new Font("Times new Roman", Font.BOLD, 14);
Calculator() {
super("Calculator");
setDesign();
setSize(380, 250);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(5,5);
setLayout(grid);
for(int i = 0; i < 4; i++)
function[i] = false;
FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);
FlowLayout f2 = new FlowLayout(FlowLayout.CENTER,1,1);
for(int i = 0; i < 5; i++)
row[i] = new JPanel();
row[0].setLayout(f1);
for(int i = 1; i < 5; i++)
row[i].setLayout(f2);
for(int i = 0; i < 19; i++) {
button[i] = new JButton();
button[i].setText(buttonString[i]);
button[i].setFont(font);
button[i].addActionListener(this);
button[i].addMouseListener(this);
}
display.setFont(font);
display.setEditable(false);
display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
display.setPreferredSize(displayDimension);
for(int i = 0; i < 14; i++)
button[i].setPreferredSize(regularDimension);
for(int i = 14; i < 18; i++)
button[i].setPreferredSize(rColumnDimension);
button[18].setPreferredSize(zeroButDimension);
row[0].add(display);
add(row[0]);
for(int i = 0; i < 4; i++)
row[1].add(button[i]);
row[1].add(button[14]);
add(row[1]);
for(int i = 4; i < 8; i++)
row[2].add(button[i]);
row[2].add(button[15]);
add(row[2]);
for(int i = 8; i < 12; i++)
row[3].add(button[i]);
row[3].add(button[16]);
add(row[3]);
row[4].add(button[18]);
for(int i = 12; i < 14; i++)
row[4].add(button[i]);
row[4].add(button[17]);
add(row[4]);
setVisible(true);
}
public void clear() {
try {
display.setText("");
for(int i = 0; i < 4; i++)
function[i] = false;
for(int i = 0; i < 2; i++)
temporary[i] = 0;
} catch(NullPointerException e) {
}
}
public void getSqrt() {
try {
double value = Math.sqrt(Double.parseDouble(display.getText()));
display.setText(Double.toString(value));
} catch(NumberFormatException e) {
}
}
public void getPosNeg() {
try {
double value = Double.parseDouble(display.getText());
if(value != 0) {
value = value * (-1);
display.setText(Double.toString(value));
}
else {
}
} catch(NumberFormatException e) {
}
}
public void getResult() {
double result = 0;
temporary[1] = Double.parseDouble(display.getText());
String temp0 = Double.toString(temporary[0]);
String temp1 = Double.toString(temporary[1]);
try {
if(temp0.contains("-")) {
String[] temp00 = temp0.split("-", 2);
temporary[0] = (Double.parseDouble(temp00[1]) * -1);
}
if(temp1.contains("-")) {
String[] temp11 = temp1.split("-", 2);
temporary[1] = (Double.parseDouble(temp11[1]) * -1);
}
} catch(ArrayIndexOutOfBoundsException e) {
}
try {
if(function[2] == true)
result = temporary[0] * temporary[1];
else if(function[3] == true)
result = temporary[0] / temporary[1];
else if(function[0] == true)
result = temporary[0] + temporary[1];
else if(function[1] == true)
result = temporary[0] - temporary[1];
display.setText(Double.toString(result));
resultPrompted = true;
for(int i = 0; i < 4; i++)
function[i] = false;
} catch(NumberFormatException e) {
}
}
public final void setDesign() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
}
}
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == button[0])
display.append("7");
if(ae.getSource() == button[1])
display.append("8");
if(ae.getSource() == button[2])
display.append("9");
if(ae.getSource() == button[3]) {
//add function[0]
temporary[0] = Double.parseDouble(display.getText());
function[0] = true;
display.setText("");
}
if(ae.getSource() == button[4])
display.append("4");
if(ae.getSource() == button[5])
display.append("5");
if(ae.getSource() == button[6])
display.append("6");
if(ae.getSource() == button[7]) {
//subtract function[1]
temporary[0] = Double.parseDouble(display.getText());
function[1] = true;
display.setText("");
}
if(ae.getSource() == button[8])
display.append("1");
if(ae.getSource() == button[9])
display.append("2");
if(ae.getSource() == button[10])
display.append("3");
if(ae.getSource() == button[11]) {
//multiply function[2]
temporary[0] = Double.parseDouble(display.getText());
function[2] = true;
display.setText("");
}
if(ae.getSource() == button[12])
display.append(".");
if(ae.getSource() == button[13]) {
//divide function[3]
temporary[0] = Double.parseDouble(display.getText());
function[3] = true;
display.setText("");
}
if(ae.getSource() == button[14])
clear();
if(ae.getSource() == button[15])
getSqrt();
if(ae.getSource() == button[16])
getPosNeg();
if(ae.getSource() == button[17])
getResult();
if(ae.getSource() == button[18])
display.append("0");
}
public static void main(String[] arguments) {
Calculator c = new Calculator();
}
#Override
public void mouseClicked(MouseEvent e) {
}
public void mousePressed (MouseEvent event){
if(resultPrompted == true){
clear();
resultPrompted = false;
}
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
That is expected behavior since you aren't clearing the text in any situation. You need to maintain state of your application (maybe use a flag) and then depending on the state of your application, either clear or append text

using toString from other methods

I am trying to output the information from the Salaried class in the EmployeesApplet class using the toString method in Salaried, however i keep receiving the error
EmployeesApplet.java:292: error: non-static method toString() cannot be referenced from a static context
ta.append(Salaried.toString());
^
How do i get around this error to display the information correctly?
here is the Salaried class
public class Salaried extends Employee
{
private double weekly_salary;
public Salaried(String first_name, String last_name, int e, double w ) // one constructor
{
super(first_name,last_name, e);
weekly_salary = w;
}
public String toString()
{
return super.toString() + " \nWeekly Salary" + weekly_salary ;
} // toString method
}
and here is the EmployeesApplet class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EmployeesApplet extends JApplet implements ActionListener
{
public JButton sd = new JButton ("Salaried");
public JButton hr = new JButton ("Hourly");
public JButton cm = new JButton ("Commissioned");
public JButton cl = new JButton ("Clear");
private final int FIELDS = 8,
FIELD_WIDTH = 20;
private String[] strings = new String[FIELDS];
private TextFieldWithLabel[] tf = new TextFieldWithLabel[FIELDS];
private JTextArea ta = new JTextArea(5,25);
String[] s = {"First Name", "Last Name", "Employee ID", "(a) Salaried: Weekly Salary", "(b1) Hourly 1: Rate Per Hour",
"(b2) Hourly 2: Hours Worked" , "(c1) Commissioned: Rate", "(c2) Commissioned: Gross Sales" };
public void init()
{
this.setSize(420, 310);
//----------------------
// Set up the Structure
//----------------------
Container c = getContentPane();
JPanel f = new JPanel(new FlowLayout());
JPanel b = new JPanel(new BorderLayout(2,0));
JPanel glb = new JPanel(new GridLayout(8,1,0,2));
JPanel gtf = new JPanel(new GridLayout(8,1,0,2));
JPanel flb = new JPanel(new FlowLayout());
// Add FlowLayout to the container
c.add(f);
// Add BorderLayout to the FlowLayout
f.add(b);
//---------------------------------------
//Add JPanels to the BorderLayout regions
//---------------------------------------
// Add JLables to GridLayout in West
b.add(glb, BorderLayout.WEST);
for (int i = 0; i < tf.length; i++)
{
tf[i] = new TextFieldWithLabel(s[i], FIELD_WIDTH);
glb.add(tf[i].getLabel());
}
// Add JTextFeilds to GridLayout in East
b.add(gtf, BorderLayout.EAST);
for (int i = 0; i < tf.length; i++)
{
tf[i] = new TextFieldWithLabel(s[i], FIELD_WIDTH);
tf[i].getTextField();
gtf.add(tf[i].getTextField());
}
// Add JButtons to FlowLayout in South
b.add(flb, BorderLayout.SOUTH);
flb.add(sd);
flb.add(hr);
flb.add(cm);
flb.add(cl);
sd.addActionListener(this);
hr.addActionListener(this);
cm.addActionListener(this);
cl.addActionListener(this);
// Add JTextArea and make it not editable
f.add(ta);
ta.setEditable(false);
}
//---------------------------------------
// Read all the JTextFields and
// save the contents in a parallel array
//---------------------------------------
private void readFields()
{
for (int i = 0; i < tf.length; i++) // or FIELDS
strings[i] = tf[i].getText();
}
private boolean fieldsExist(int i, int i2)
{
if(i == 0 && i2 == 3) // Checks Salaried worker
{
if(tf[0].getText() == null || tf[0].getText().length() == 0)
{
showStatus("First Name field is empty"); // Diplays error message in status area
tf[0].getTextField().requestFocus(); // Places focus in JTextField
return false;
}
else if(tf[1].getText() == null || tf[1].getText().length() == 0)
{
showStatus("Last Name field is empty");
tf[1].getTextField().requestFocus();
return false;
}
else if(tf[2].getText() == null || tf[2].getText().length() == 0)
{
showStatus("Employee ID field is empty");
tf[2].getTextField().requestFocus();
return false;
}
else if(tf[3].getText() == null || tf[3].getText().length() == 0)
{
showStatus("(a)Salried: Weekly Salary field is empty");
tf[3].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 0 && i2 == 2) // Checks Hourly worker
{
if(tf[0].getText() == null || tf[0].getText().length() == 0)
{
showStatus("First Name field is empty");
tf[0].getTextField().requestFocus();
return false;
}
else if(tf[1].getText() == null || tf[1].getText().length() == 0)
{
showStatus("Last Name field is empty");
tf[1].getTextField().requestFocus();
return false;
}
else if(tf[2].getText() == null || tf[2].getText().length() == 0)
{
showStatus("Employee ID field is empty");
tf[2].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 4 && i2 == 5) // Checks Hourly worker the second time
{
if(tf[4].getText() == null || tf[4].getText().length() == 0)
{
showStatus("(b1) Hourly 1: Rate Per Hour field is empty");
tf[5].getTextField().requestFocus();
return false;
}
else if(tf[5].getText() == null || tf[5].getText().length() == 0)
{
showStatus("(b2) Hourly 2: Hours Worked field is empty");
tf[5].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 0 && i2 == 2) // Checks Commissioned worker
{
if(tf[0].getText() == null || tf[0].getText().length() == 0)
{
showStatus("First Name field is empty");
tf[0].getTextField().requestFocus();
return false;
}
else if(tf[1].getText() == null || tf[1].getText().length() == 0)
{
showStatus("Last Name field is empty");
tf[1].getTextField().requestFocus();
return false;
}
else if(tf[2].getText() == null || tf[2].getText().length() == 0)
{
showStatus("Employee ID field is empty");
tf[2].getTextField().requestFocus();
return false;
}
else
return true;
}
if(i == 6 && i2 == 7) // Checks Commissioned second time
{
if(tf[6].getText() == null || tf[6].getText().length() == 0)
{
showStatus("(c1)Commissioned: Rate field is empty");
tf[0].getTextField().requestFocus();
return false;
}
else if(tf[7].getText() == null || tf[7].getText().length() == 0)
{
showStatus("(c2)Commissioned: Ratefield is empty");
tf[1].getTextField().requestFocus();
return false;
}
else
return true;
}
return false;
}
private boolean fieldsEmpty(int i, int i2, String[] a)
{
if(i == 4 && i2 == 7) // checks salaried
{
for (int index = 4; index <= 7; index++)
{
if(tf[index].getText().length() != 0)
{
showStatus( a[index] + " should be empty"); // Diplays error message in status area
tf[index].getTextField().requestFocus(); // Places focus in JTextField
return true;
}
else return false;
} // end for
} // end if
if (i == 3 && i2 == 3) // checks hourly first time
{
if(tf[3].getText().length() != 0)
{
showStatus(a[3] + " field should be empty");
tf[3].getTextField().requestFocus();
return true;
}
} // end if
if(i == 6 && i2 == 7) // checks hourly second time
{
for (int index = 6; index <= 7; index++)
{
if(tf[index].getText().length() != 0)
{
showStatus(a[index] + " field should be empty");
tf[index].getTextField().requestFocus();
return true;
}
} // end for
} // end if
if(i == 3 && i2 == 5) // checks commissioned
{
for (int index = 3; index <= 5; index++)
{
if(tf[index].getText().length() != 0)
{
showStatus(a[index] + " field should be empty");
tf[index].getTextField().requestFocus();
return true;
}
} // end for
} // end if
return false;
}
public void actionPerformed(ActionEvent e)
{
showStatus("");
if (e.getSource() == cl) // Executes clear button is clicked
{
for (int i = 0; i < FIELDS; i++)
{
tf[i].getTextField().setText("");
tf[0].getTextField().requestFocus();
}
} // End clear if
if (e.getSource() != cl)
{
if(e.getSource() == sd) // checks for salaried employee
{
showStatus("Salaried");
fieldsExist(0,3);
fieldsEmpty(4,7, s);
ta.append(Salaried.toString());
} // end salaried
if(e.getSource() == hr) // checks for hourly employee
{
showStatus("Hourly");
fieldsExist(0,2);
fieldsExist(4,5);
fieldsEmpty(3,3, s);
fieldsEmpty(6,7, s);
} // end hourly
if(e.getSource() == cm) // checks for commissioned employee
{
showStatus("Commissioned");
fieldsExist(0,2);
fieldsExist(6,7);
fieldsEmpty(3,5, s);
} // end commisssioned
} // end if
} // End of actionPerformed
}
As the error states, toString() is not static, you need to run it on an instance of Salaried. e.g.
Salaried s = new Salaried();
s.toString(); // should work...
Without relevant section from EmployeeApplet I cannot advise further, note ta.append(Salaried.toString()); in the error message you posted, does not appear to correspond to fragment of EmployeeApplet you gave...

Minimax algorithm always returns one number

I have got a problem with minimax algorithm. I want to make tic tac toe game with AI. I used JFrame to make that.
So my minimax algorithm returns always number 9 and I don't know why. What's wrong ?
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Zadanie2 extends JFrame implements ActionListener {
/**
*
*/
JButton button0 = new JButton("");
JButton button1 = new JButton("");
JButton button2 = new JButton("");
JButton button3 = new JButton("");
JButton button4 = new JButton("");
JButton button5 = new JButton("");
JButton button6 = new JButton("");
JButton button7 = new JButton("");
JButton button8 = new JButton("");
JButton button9 = new JButton("");
int playerSign = 1;
String computerMark, opponentMark;
public static final long serialVersionUID = 1L;
JButton[] buttonArray = { button0, button1, button2, button3, button4,
button5, button6, button7, button8, button9 };
Object[] options = { "GRAJ OD NOWA", "ZAKOŃCZ GRĘ" };
Object[] startOptions = { "GRACZ", "KOMPUTER", "OPUŚĆ GRĘ" };
boolean canMove;
boolean computerStarted;
int bb = 1;
public Zadanie2() {
super("KÓŁKO I KRZYŻYK");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setResizable(false);
setLocation(470,400);
setLayout(new GridLayout(3,3));
for(int i = 1; i <= 9; i++){
add(add(buttonArray[i]));
buttonArray[i].addActionListener(this);
}
setVisible(true);
int y = JOptionPane.showOptionDialog(null,"WYBIERZ KTO MA ZACZĄĆ GRĘ","WIADOMOŚĆ", JOptionPane.INFORMATION_MESSAGE,
JOptionPane.INFORMATION_MESSAGE,
null,
startOptions,
startOptions[0]);
if (y == 2) {
System.exit(1);
}
if (y == 1) { // COMPUTER
computerStarted = true;
computerMark = "X";
opponentMark = "O";
canMove = true;
computerMove();
}
if (y == 0) { // PLAYER
computerStarted = false;
computerMark = "O";
opponentMark = "X";
}
}
public static void main(String[] args) {
new Zadanie2();
}
public void close() {
playerSign = 1;
dispose();
}
private void computerMove() {
if(canMove){
System.out.println("AI: "+AI(buttonArray));
buttonArray[AI(buttonArray)].doClick();
}
canMove = false;
}
private int AI(JButton[] buttonArray2){
int ruch, i, m, mmx;
ruch = 0;
mmx = -10;
for(i = 1; i < 9; i++)
if(buttonArray[i].getText() == "");
{
buttonArray[i].setText(computerMark);
m = minimax(buttonArray, computerMark);
buttonArray[i].setText("");
if (m > mmx) {
mmx = m;
ruch = i;
}
}
return ruch;
}
public int minimax(JButton[] buttonArray,String gracz){
int m, mmx;
if(win(buttonArray,gracz)) return (gracz == computerMark) ? 1 : -1;
if(tie(buttonArray)){
return 0;}
gracz = (gracz == computerMark) ? opponentMark : computerMark;
mmx = (gracz == opponentMark) ? 10 : -10;
for(int i = 1; i <= 9; i++)
if(buttonArray[i].getText() == "")
{
buttonArray[i].setText(gracz);
m = minimax(buttonArray,gracz);
buttonArray[i].setText("");
if(((gracz == opponentMark) && (m < mmx)) || ((gracz == computerMark) && (m > mmx))){mmx = m;}
}
return mmx;
}
private void checkWin() {
if(win(buttonArray,"X")){
winX();
}
if(win(buttonArray,"O")){
winO();
}
if(tie(buttonArray)){
sayTie();
}
}
private void winX() {
int n = JOptionPane.showOptionDialog(null, "WYGRAŁ GRACZ X ",
"WIADOMOŚĆ", JOptionPane.INFORMATION_MESSAGE,
JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (n == 0) {
close();
new Zadanie2();
}
if (n == 1) {
System.exit(1);
}
dispose();
}
private void winO() {
int n = JOptionPane.showOptionDialog(null, "WYGRAŁ GRACZ O ",
"WIADOMOŚĆ", JOptionPane.INFORMATION_MESSAGE,
JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (n == 0) {
close();
new Zadanie2();
}
if (n == 1) {
System.exit(1);
}
dispose();
}
private void sayTie() {
int n = JOptionPane.showOptionDialog(null, "REMIS! ", "WIADOMOŚĆ",
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
if (n == 0) {
close();
new Zadanie2();
}
if (n == 1) {
System.exit(1);
}
dispose();
}
public boolean tie(JButton[] buttonArray2){
for(int i = 1; i <= 9; i++){
if(buttonArray2[i].getText() == ""){
return false;
}
}
return true;
}
private boolean win(JButton[] buttonArray2, String g) {
if (buttonArray2[1].getText() == buttonArray2[2].getText()
&& buttonArray2[1].getText() == buttonArray2[3].getText()
&& buttonArray2[2].getText() == buttonArray2[3].getText() && buttonArray2[1].getText() == g) {
return true;
}
if (buttonArray2[3].getText() == buttonArray2[7].getText()
&& buttonArray2[3].getText() == buttonArray2[5].getText()
&& buttonArray2[7].getText() == buttonArray2[5].getText() && buttonArray2[3].getText() == g) {
return true;
}
if (buttonArray2[7].getText() == buttonArray2[8].getText()
&& buttonArray2[7].getText() == buttonArray2[9].getText()
&& buttonArray2[8].getText() == buttonArray2[7].getText() && buttonArray2[7].getText() == g) {
return true;
}
if (buttonArray2[4].getText() == buttonArray2[5].getText()
&& buttonArray2[4].getText() == buttonArray2[6].getText()
&& buttonArray2[5].getText() == buttonArray2[6].getText() && buttonArray2[4].getText() == g) {
return true;
}
if (buttonArray2[1].getText() == buttonArray2[5].getText()
&& buttonArray2[1].getText() == buttonArray2[9].getText()
&& buttonArray2[5].getText() == buttonArray2[9].getText() && buttonArray2[1].getText() == g) {
return true;
}
if (buttonArray2[1].getText() == buttonArray2[4].getText()
&& buttonArray2[1].getText() == buttonArray2[7].getText()
&& buttonArray2[4].getText() == buttonArray2[7].getText() && buttonArray2[1].getText() == g) {
return true;
}
if (buttonArray2[2].getText() == buttonArray2[8].getText()
&& buttonArray2[2].getText() == buttonArray2[5].getText()
&& buttonArray2[8].getText() == buttonArray2[5].getText() && buttonArray2[2].getText() == g) {
return true;
}
if (buttonArray2[3].getText() == buttonArray2[6].getText()
&& buttonArray2[3].getText() == buttonArray2[9].getText()
&& buttonArray2[6].getText() == buttonArray2[9].getText() && buttonArray2[3].getText() == g) {
return true;
}
return false;
};
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
for (int i = 1; i <= 9; i++) {
if (source == buttonArray[i] ) {
playerSign++;
if (playerSign % 2 == 0 && buttonArray[i].getText() == "") {
buttonArray[i].setText("X");
}
if (playerSign % 2 != 0 && buttonArray[i].getText() == "") {
buttonArray[i].setText("O");
}
if (computerStarted && playerSign % 2 != 0) {
canMove = true;
computerMove();
}
if (!computerStarted && playerSign % 2 == 0) {
canMove = true;
computerMove();
}
}
}
System.out.println("PS: " + playerSign);
if(playerSign > 3){
checkWin();}
}
}
Any ideas on how I may solve this problem?
You should use .equals instead of == whenever you compare two Objects.
E.g. there should be computerMark.equals(gracz) instead of gracz == computerMark.
Edit:
Also, You should replace 1 and -1 with 10 and -10 respectively here:
if(win(buttonArray,gracz)) return (gracz == computerMark) ? 1 : -1;
Reference

Java connect four victory check

I am a beginner at programming and I have been teaching myself as much as I can. I need help in a simpler way of checking for a victory instead of hard coding every possible combination.
I have no idea what to do.
here is my current code:
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class connectfour extends JFrame implements ActionListener
{
JLabel board[][] = new JLabel[8][7];
//JLabel board[] = new JLabel[64];
JButton action[] = new JButton[8];
JButton start;
JButton clear;
JFrame Frame = new JFrame();
ImageIcon red = new ImageIcon("red piece.jpeg");
ImageIcon black = new ImageIcon("blackpiece.jpeg");
boolean players = true;
//Integer[] numclick = new Integer[8];
int x;
int numclick1 = 7;
int numclick2 = 7;
int numclick3 = 7;
int numclick4 = 7;
int numclick5 = 7;
int numclick6 = 7;
int numclick7 = 7;
int numclick0 = 7;
public connectfour()
{
Frame.setSize(100,120);
Frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
Frame.setLayout(null);
Frame.setVisible(true);
start = new JButton("Start");
start.setBounds(0,0,100,100);
start.setVisible(true);
start.addActionListener(this);
Frame.add(start);
}
public void game()
{
for(int x = 0; x < 8 ; x++)
{
action[x] = new JButton();
action[x].setSize(100,40);
action[x].setLocation((x*100) + 50, 0);
action[x].addActionListener(this);
action[x].setVisible(true);
Frame.add(action[x]);
}
/**
board[1][1] = new JLabel();
board[1][1].setBounds(50,40,100,100);
board[1][1].setVisible(true);
board[1][1].setOpaque(true);
board[1][1].setBorder(BorderFactory.createLineBorder(Color.black));
Frame.add(board[1][1]);
**/
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 7; j++)
{
board[i][j] = new JLabel();
board[i][j].setSize(100,100);
board[i][j].setLocation((i*100)+50,(j*100)+40);
board[i][j].setOpaque(true);
board[i][j].setVisible(true);
board[i][j].setBorder(BorderFactory.createLineBorder(Color.black));
Frame.add(board[i][j]);
}
}
clear = new JButton("Clear");
clear.setBounds(850,100,100,50);
clear.addActionListener(this);
clear.setVisible(true);
Frame.add(clear);
}
public void boardsize()
{
Frame.setSize(950,800);
}
public static void main(String args[])
{
new connectfour();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == start)
{
boardsize();
start.setVisible(false);
game();
}
for(x = 0;x < 8 ;x ++)
{
if(e.getSource() == action[x])
{
//numclick[x]++;
if(x == 0)
{
numclick0--;
if(players == true)
{
board[x][numclick0].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick0].setIcon(black);
players = true;
break;
}
}
if(x == 1)
{
numclick1--;
if(players == true)
{
board[x][numclick1].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick1].setIcon(black);
players = true;
break;
}
}
if(x == 2)
{
numclick2--;
if(players == true)
{
board[x][numclick2].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick2].setIcon(black);
players = true;
break;
}
}
if(x == 3)
{
numclick3--;
if(players == true)
{
board[x][numclick3].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick3].setIcon(black);
players = true;
break;
}
}
if(x == 4)
{
numclick4--;
if(players == true)
{
board[x][numclick4].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick4].setIcon(black);
players = true;
break;
}
}
if(x == 5)
{
numclick5--;
if(players == true)
{
board[x][numclick5].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick5].setIcon(black);
players = true;
break;
}
}
if(x == 6)
{
numclick6--;
if(players == true)
{
board[x][numclick6].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick6].setIcon(black);
players = true;
break;
}
}
if(x == 7)
{
numclick7--;
if(players == true)
{
board[x][numclick7].setIcon(red);
players = false;
break;
}
if(players == false)
{
board[x][numclick7].setIcon(black);
players = true;
break;
}
}
System.out.println(x);
System.out.println();
}
}
if(e.getSource() == clear)
{
for(int x = 0; x < 8; x++)
{
for(int y = 0; y < 7; y++)
{
board[x][y].setIcon(null);
numclick1 = 7;
numclick2 = 7;
numclick3 = 7;
numclick4 = 7;
numclick5 = 7;
numclick6 = 7;
numclick7 = 7;
numclick0 = 7;
players = true;
for(int j = 0; j < 8 ; j++)
{
action[j].setEnabled(true);
}
}
}
}
if(numclick0 == 0)
{
action[0].setEnabled(false);
}
if(numclick1 == 0)
{
action[1].setEnabled(false);
}
if(numclick2 == 0)
{
action[2].setEnabled(false);
}
if(numclick3 == 0)
{
action[3].setEnabled(false);
}
if(numclick4 == 0)
{
action[4].setEnabled(false);
}
if(numclick5 == 0)
{
action[5].setEnabled(false);
}
if(numclick6 == 0)
{
action[6].setEnabled(false);
}
if(numclick7 == 0)
{
action[7].setEnabled(false);
}
}
public void winner()
{
}
}
I would use a recursive method that checks the horizontal, vertical, and both diagonals.
As i was reading your code I realized you don't keep track(may have missed it) of where players are.. I recommend and array for this called grid[][] Mapping an array to your JLabels will go a long way.
Ill give an example of negative vertical check..
public Boolean checkVertical(Boolean player, int x, int y){
if(solveHelper(player, x, y, -1, 0) => 4) return true;
return false;
}
public int solveHelper(Boolean player, int x, int y, int addX, int addY){
if(x == 0 || x == size || y == 0 || y == size || grid[x][y].player != player)
return 0;
return solverHelper(player, x+addX, y+addY, addX, addY) + 1);
}
Now how can you create and use these methods for yourself?
you need to create a new methods for each of the horizontal, vertical, and both diagonals to check for all of them you call solveHelper with different properties in addX and addY that correspond with the direction you want to go. For instance, if you want to check the horizontal you need do make addY == 1 and addY == -1 with both values for addX == 0 by doing a solveHelper + solverHelper with these two values changed.
Other notes...
Some things you need to need to keep in mind is that how connect four actually runs. When you click on a row a piece falls down to the smallest unoccupied element in that particular column. Just something you should keep in mind when writing your game logic.
Cheers.

Categories