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
Related
When I attempt to draw the objects in the array it successfully displays them if there is no KeyEvent e in the header, but if KeyEvent e is in the header like is shown (and to my knowledge it needs to be in order to call the method) it does not print anything out.
How can I use the method I created that moves an object in the array if I cannot have KeyEvent e in the header?
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Field extends Applet
{
public void paint(Graphics g, KeyEvent e)
{
drawField(g,e);
}
public void drawField(Graphics g, KeyEvent e)
{
int Field[][] = new int[1000][1000];
int Roadl[][] = new int[1000][1000];
Field[100][100] = 1;
Field[100][300] = 2;
Field[100][500] = 3;
Roadl[100][500] = 500;
Field[300][100] = 4;
Roadl[300][100] = 500;
Field[600][600] = 6;
moveCar(Field,600,600,e);
for(int i = 0; i < Field.length; i++)
{
for (int k = 0; k < Field[i].length; k++)
{
if (Field[i][k] == 1)
{
VertBuilding vb1 = new VertBuilding(i,k,g);
}
else if (Field[i][k] == 2)
{
HorizBuilding hb1 = new HorizBuilding(i,k,g);
}
else if (Field[i][k] == 3)
{
VertRoad vr1 = new VertRoad(i,k,Roadl[i][k],g);
}
else if (Field[i][k] == 4)
{
HorizRoad hr1 = new HorizRoad(i,k,Roadl[i][k],g);
}
else if (Field[i][k] == 5)
{
Coin c1 = new Coin(i,k,g);
}
else if (Field[i][k] == 6)
{
HorizCar car1 = new HorizCar(i,k,g);
}
else if (Field[i][k] == 7)
{
VertCar car1 = new VertCar(i,k,g);
}
}
}
}
public void moveCar(int[][] arr1, int i, int k, KeyEvent e)
{
i += keyTypedH(e);
k += keyTypedV(e);
arr1[i][k] = carD(e);
}
public int keyTypedV (KeyEvent e) {
char c = e.getKeyChar();
int y = 0;
if (c == 's')
{
y+=10;
}
else if (c == 'w')
{
y-=10;
}
return y;
}
public int keyTypedH (KeyEvent e) {
char c = e.getKeyChar();
int x = 0;
if (c == 'a')
{
x-=10;
}
else if (c == 'd')
{
x+=10;
}
return x;
}
public int carD (KeyEvent e) {
char c = e.getKeyChar();
int carLocation = 0;
if (c == 'a')
{
carLocation = 6;
}
else if (c == 'd')
{
carLocation = 6;
}
else if (c == 's')
{
carLocation = 7;
}
else if (c == 'w')
{
carLocation = 7;
}
return carLocation;
}
}
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
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 + "]";
}
}
I'm making a fighting game and I want the actions of the player to be timed so you can't spam the attack key and win easily.
Here is where I do the keyboard stuff and delay. It does delay the first time, but then it the delay slowly decreases in time and ends up being 0 and lets you spam the key. As you can see I've done many things to try and stop the key from registering in the delay etc.
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (isAction == false) {
if (key == KeyEvent.VK_LEFT) {
dx = -1;
if (nHeroX < -10) {
dx = 0;
}
isRight = false;
isMoving = true;
} else if (key == KeyEvent.VK_RIGHT) {
dx = 1;
if (nHeroX > 1200) {
dx = 0;
}
isRight = true;
isMoving = true;
} else if (key == KeyEvent.VK_C) {
dx = 0;
isAction = true;
isMoving = false;
isBlock = true;
nImage = 1;
} else if (key == KeyEvent.VK_X) {
dx = 0;
isAction = true;
isMoving = false;
isWeak = true;
nImage = 2;
} else if (key == KeyEvent.VK_Z) {
dx = 0;
isAction = true;
isMoving = false;
isStrong = true;
nImage = 3;
} else if (key == KeyEvent.VK_P) {
if (!pause) {
pause = true;
} else if (pause) {
pause = false;
}
}
}
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT && !isAction) {
dx = 0;
isMoving = false;
nState = nImage = 1;
} else if (key == KeyEvent.VK_C && !isWeak && !isStrong) {
delayTask = new DelayTask();
tmrDelay.schedule(delayTask, 0, 500);
} else if (key == KeyEvent.VK_X && !isBlock && !isStrong) {
z = new DelayTask();
tmrDelay.schedule(z, 0, 450);
} else if (key == KeyEvent.VK_Z && !isBlock && !isWeak) {
x = new DelayTask();
tmrDelay.schedule(x, 0, 1200);
}
nImgNum = (int) (Math.random() * 6 + 1);
nDelay = 0;
}
//http://www.javaprogrammingforums.com/java-se-api-tutorials/883-how-use-tmrDelay-java.html
class DelayTask extends TimerTask {
public int nTimes = 0;
#Override
public void run() {
nTimes++;
if (nTimes == 2) {
isAction = isBlock = isStrong = isWeak = false;
nState = nImage = 1;
}
}
}
Can someone explain why my delay is messed up? Thank you.
Also this code:
private class Keys extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
hero.keyPressed(e);
}
#Override
public void keyReleased(KeyEvent e) {
hero.keyReleased(e);
if (hero.getPause()) {
repaint();
}
}
}
The simplest way to do this is just to remember the last time.
So:
private long lastTime = 0;
void doAction() {
long timeNow = System.currentTimeMillis()
if (lastTime + MIN_DELAY < timeNow) {
return;
}
lastTime = timeNow;
// Do action
}
All the stuff with timers etc is just approaching this from a much more complicated architecture than you need to.
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.