I'm trying to set an int, defined in the class, to 0, 5 seconds after it has been changed to more than 0. Any help would be greatly appreciated!
I have a program where users have to input an addition to a score.
private void inputResponse(int pNum) {
Patient p = null;
p = patientList.get(pNum);
Map<String, List<Double>> pData = sEWSTracker.get(p);
List<Double> sEp = pData.get("SEW");
Double sEWS = sEp.get(sEp.size() - 1);
Component frame = null;
Object[] response = {"Alert", "Verbal", "Pain", "Unresponsive"};
String r = (String) JOptionPane.showInputDialog(
frame,
"Please input the patient’s response external stimulus:\n", "Please Report Patient's Response Level",
JOptionPane.PLAIN_MESSAGE, null,
response, response[0]);
int reACT = 0;
if (r.equals("Verbal")) {
if (pNum == 0) {
p0checked = 1;
}
if (pNum == 1) {
p1checked = 1;
}
if (pNum == 2) {
p2checked = 1;
}
if (pNum == 3) {
p3checked = 1;
}
if (pNum == 4) {
p4checked = 1;
}
if (pNum == 4) {
p5checked = 1;
}
}
if (r.equals("Pain")) {
if (pNum == 0) {
p0checked = 2;
}
if (pNum == 1) {
p1checked = 2;
}
if (pNum == 2) {
p2checked = 2;
}
if (pNum == 3) {
p3checked = 2;
}
if (pNum == 4) {
p4checked = 2;
}
if (pNum == 4) {
p5checked = 2;
}
}
if (r.equals("Unresponsive")) {
if (pNum == 0) {
p0checked = 3;
}
if (pNum == 1) {
p1checked = 3;
}
if (pNum == 2) {
p2checked = 3;
}
if (pNum == 3) {
p3checked = 3;
}
if (pNum == 4) {
p4checked = 3;
}
if (pNum == 4) {
p5checked = 3;
}
}
Double sEWP = (reACT * 1.0) + sEWS;
List<Double> soEWS = pData.get("SEW");
soEWS.add(sEWP);
this.repaint();
sEWSreact(pNum);
}
Until they do the representation has a little message on it saying "Partial Score":
(for example)
if (p0checked == 0) {
g2.setColor(darkOrange);
g2.fillRoundRect(250, 152, 120, 35, 10, 10);
g2.setColor(mellowOrange);
g2.fillRoundRect(252, 154, 116, 31, 10, 10);
g2.setColor(darkBlue);
g2.setFont(helvetica1);
g2.drawString("Partial", 272, 170);
g2.setFont(verdanda4);
g2.setColor(Color.white);
g2.drawString("Click here to update", 258, 182);
}
}
And then a timer that resets the additional score to 0, in order to make the partial score notice come back and the score go back down to the original. ...however, nothing happens
if (p0checked > 0) {
Timer tim = new Timer(5 * 1000, new ActionListener() {#Override
public void actionPerformed(ActionEvent e) {
if (timSec >= 1) {
p0checked = 0;
}
timSec++;
}
});
tim.start();
}
timSec is defined (as 0) in the class also.
Related
I am making SOS game with "stack".No other data structures such as normal array, string etc.
Gameboard size 3*6 and I am using random for determining letters.
But I don't know is the game over or not.
How can I control is there any horizontal or vertical sos at the console
Here is my code(I am beginner)
public static void main(String[] args) {
Random rnd = new Random();
Stack S1 = new Stack(6);
Stack S2 = new Stack(6);
Stack S3 = new Stack(6);
Stack ts1 = new Stack(6);
Stack ts2 = new Stack(6);
Stack ts3 = new Stack(6);
int Round = 0;
int satir;
boolean winner = false;
// for S1
int i = 0;
while (i != 6) { // 6time
i++;
// System.out.println(i);
if (rnd.nextBoolean()) {
S1.push("S");
} else {
S1.push("O");
}
}
// for S2
i = 0;
while (i != 6) {
i++;
if (rnd.nextBoolean()) {
S2.push("S");
} else {
S2.push("O");
}
}
// for S3
i = 0;
while (i != 6) {
i++;
if (rnd.nextBoolean()) {
S3.push("S");
} else {
S3.push("O");
}
}
int a = 0, b = 0, c = 0;
int tempa = a;
int tempb = b;
int tempc = c;
while (!winner) {
System.out.println("User" + ((Round % 2) + 1) + ":"); // User1:
// User2:
satir = rnd.nextInt(3) + 1;
if (satir == 1 && a != 6) {
a++;
}
if (satir == 2 && b != 6) {
b++;
}
if (satir == 3 && c != 6) {
c++;
}
tempa = a;
tempb = b;
tempc = c;
System.out.print("S1 ");
while (a > 0) { // S1 in icini yazdir bosalt ts1e kaydet
System.out.print(S1.peek() + " ");
ts1.push(S1.pop());
a--;
}
a = tempa;
while (!ts1.isEmpty()) { // S1i tekrar doldur
S1.push(ts1.pop());
}
System.out.println();
System.out.print("S2 ");
while (b > 0) { // S2 in icini yazdir bosalt ts1e kaydet
System.out.print(S2.peek() + " ");
ts2.push(S2.pop());
b--;
}
b = tempb;
while (!ts2.isEmpty()) { // S2i tekrar doldur
S2.push(ts2.pop());
}
System.out.println();
System.out.print("S3 ");
while (c > 0) { // S3 in icini yazdir bosalt ts1e kaydet
System.out.print(S3.peek() + " ");
ts3.push(S3.pop());
c--;
}
c = tempc;
while (!ts3.isEmpty()) { // S3i tekrar doldur
S3.push(ts3.pop());
}
System.out.println();
// check if there is sos winner=true;
if (a > 2) { //check S1 Horizontal
for (int yatay1 = 0; yatay1 < a; yatay1++) {
if (S1.peek().equals("S")) {
ts1.push(S1.pop());
if (S1.peek().equals("O")) {
ts1.push(S1.pop());
if (S1.peek().equals("S")) {
System.out.println("SOS-wow");
winner = true;
} else {
while (!ts1.isEmpty()) {
S1.push(ts1.pop());
}
}
} else {
S1.push(ts1.pop());
}
}
}
}
Round++;
} // end of loop
}
I am working on code for an assignment in which I have to make Wheel of Fortune, I am having trouble with building the string that will be shown to the user after each guess. I have the wheel spin working but I just can't seem to figure how to build the string. I can also answer any questions about this if you have any. Any help will be much appreciated. Here is my code so far:
class WheelOfFortune3 {
public static void main(String[] args) {
int result, location, newLocation, numGuess = 0;
String puzzle, guess;
String sub[] = new String[26];
for (int i = 0; i < sub.length; i++) {
sub[i] = "_";
}
result = wheelResult();
System.out.println("You spun $" + result);
puzzle = getPuzzle();
System.out.println(puzzle);
do {
guess = In.getString();
location = checkGuess(puzzle, guess);
if (location == -1) {
System.out.println("Incorrect guess");
}
if (location >= 0 && location <= 25) {
System.out.println("Correct guess");
newLocation = location + 1;
sub[numGuess] = puzzle.substring(location, newLocation);
for (int i = 0; i <= 10; i++) {
System.out.print(sub[i] + " ");
}
System.out.println("");
numGuess = numGuess + 1;
System.out.println(numGuess);
System.out.println(sub.length);
}
}
while (numGuess < sub.length);
}
public static int checkGuess(String puzzle, String guess) {
String word = puzzle;
int location;
location = word.indexOf(guess);
return location;
}
public static int wheelResult() {
int result;
int[] wheelSpin = new int[1];
wheelSpin[0] = (int)(24 * Math.random());
if (wheelSpin[0] == 1 || wheelSpin[0] == 18 || wheelSpin[0] == 22) {
result = 200;
return result;
} else if (wheelSpin[0] == 2 || wheelSpin[0] == 5) {
result = 900;
return result;
} else if (wheelSpin[0] == 0 || wheelSpin[0] == 3 || wheelSpin[0] == 15) {
result = 250;
return result;
} else if (wheelSpin[0] == 4 || wheelSpin[0] == 6 || wheelSpin[0] == 12 || wheelSpin[0] == 16) {
result = 300;
return result;
} else if (wheelSpin[0] == 7) {
result = 1500;
return result;
} else if (wheelSpin[0] == 9 || wheelSpin[0] == 11) {
result = 700;
return result;
} else if (wheelSpin[0] == 10 || wheelSpin[0] == 14 || wheelSpin[0] == 21) {
result = 500;
return result;
} else if (wheelSpin[0] == 13) {
result = 5000;
return result;
} else if (wheelSpin[0] == 23 || wheelSpin[0] == 19) {
result = 600;
return result;
} else if (wheelSpin[0] == 8 || wheelSpin[0] == 20) {
result = 100;
return result;
} else if (wheelSpin[0] == 17) {
result = 17;
return result;
}
return -1;
}
public static String getPuzzle() {
String puzzle;
//a long ride
return "A long ride";
//01234567890
}
}
This can be done using a List of Characters and the .contains() method like so:
List<Character> guessedCharacters = new ArrayList<>();
each time a player guesses a letter, add that letter to
the guessedCharacters List like this: guessedCharacters.add(char);
Then you can do something like this to generate the String to output to the player:
StringBuilder toShowSB = new StringBuilder();
for(int i=0,n=puzzle.length;i<n;i++){
if(guessedCharacters.contains(puzzle.charAt(i))){
toShowSB.append(puzzel.charAt(i));
}else{
toShowSB.append("_");
}
}
String toShow = toShowSB.toString();
This will create a String that holds all of the guessed letters in their places and an underscore denoting characters that have not been properly guessed yet.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I'm trying to recreate a printer in java,I'm fairly new to programming so I'm using huge if else blocks inside a single function to dictate the logic of the program, I'm noticing this is creating a mass of code inside the same function, I was wondering if there was a more eloquent/efficient way of doing this, printer class below. Logic for the printer isn't too important, but just to show anyway, one is a double sided printer one isn't, and logic is in charge of checking toner levels and making sure pages printed are in line with printer being double sided or not.
package com.company;
public class Printer {
private String name;
private double tonerLevel = 100;
private int ammountOfPaper;
private int numberOfPagesPrinted;
private boolean isDoubleSided;
public Printer(String name, double tonerLevel, int ammountOfPaper, boolean isDoubleSided) {
this.name = name;
if(tonerLevel >= 0 && tonerLevel <= 100) {
this.tonerLevel = tonerLevel;
}
this.ammountOfPaper = ammountOfPaper;
this.isDoubleSided = isDoubleSided;
}
private boolean isOutOfToner(double numberToPrint) {
if((tonerLevel - (numberToPrint / 2) < 0)) {
return true;
}
else {
return false;
}
}
private boolean isOutOfPaper(double numberToPrint) {
if(((ammountOfPaper - numberToPrint) < 0)) {
return true;
}
else {
return false;
}
}
private boolean twoSideNoPaperEven(double numberToPrint) {
if((ammountOfPaper - ((int) numberToPrint / 2)) < 0 ) {
return true;
}
else {
return false;
}
}
private boolean twoSideNoPaperOdd(double numberToPrint) {
if(((ammountOfPaper - ((int) numberToPrint / 2)) - 1) < 0) {
return true;
}
else {
return false;
}
}
public void printPages(double numberToPrint) {
if(isDoubleSided == false) {
if(tonerLevel == 0) {
System.out.println("Out of toner");
}
if(ammountOfPaper == 0) {
System.out.println("Out of Paper");
}
if(isOutOfToner(numberToPrint) && (tonerLevel != 0)) {
double difference = tonerLevel * 2;
numberToPrint = difference;
ammountOfPaper -= numberToPrint;
System.out.println("Will run out of toner after this print, able to print " + (int) numberToPrint +
" pages");
tonerLevel = 0;
}
if(isOutOfPaper(numberToPrint) && (ammountOfPaper != 0)) {
double different = ammountOfPaper - numberToPrint;
numberToPrint = numberToPrint + different;
System.out.println("Will run out of paper after this print, printing " + (int) numberToPrint + " pages");
ammountOfPaper = 0;
}
else if(!isOutOfToner(numberToPrint) && (!isOutOfPaper(numberToPrint))) {
ammountOfPaper -= numberToPrint;
tonerLevel = tonerLevel - (numberToPrint / 2);
showPages(numberToPrint);
}
}
else if(isDoubleSided = true) {
if (numberToPrint % 2 == 0) {
if(tonerLevel == 0) {
System.out.println("Out of Toner");
}
if(ammountOfPaper == 0) {
System.out.println("Out of Paper");
}
if(twoSideNoPaperEven(numberToPrint) && (ammountOfPaper != 0)) {
ammountOfPaper -= numberToPrint / 2;
System.out.println("There is no Paper");
}
else if(!twoSideNoPaperEven(numberToPrint)) {
tonerLevel = tonerLevel - (numberToPrint / 2);
ammountOfPaper -= numberToPrint / 2;
showPages(numberToPrint);
}
} else {
if(tonerLevel == 0) {
System.out.println("Out of Toner");
}
if(ammountOfPaper == 0) {
System.out.println("Out of Paper");
}
if(twoSideNoPaperOdd(numberToPrint) && (ammountOfPaper != 0)) {
System.out.println("There is no paper");
ammountOfPaper = (ammountOfPaper - ((int) numberToPrint / 2)) - 1;
ammountOfPaper = 0;
}
else if(!twoSideNoPaperOdd(numberToPrint)) {
tonerLevel = tonerLevel - (numberToPrint / 2);
ammountOfPaper = (ammountOfPaper - ((int) numberToPrint / 2)) - 1;
showPages(numberToPrint);
}
}
}
}
public void showPages(double numberToPrint) {
System.out.println("Printing " + (int) numberToPrint + " Pages, paper remaining is: " + this.ammountOfPaper
+ " Toner level is: " + this.tonerLevel);
}
public void refillToner() {
tonerLevel = 100;
}
public void refillPaper(int paper) {
if(paper > 50) {
System.out.println("Cannot put in more paper");
}
else {
this.ammountOfPaper += paper;
}
}
public int getAmmountOfPaper() {
return ammountOfPaper;
}
public double getTonerLevel() {
return tonerLevel;
}
public void setTonerLevel(double tonerLevel) {
this.tonerLevel = tonerLevel;
}
public void setAmmountOfPaper(int ammountOfPaper) {
this.ammountOfPaper = ammountOfPaper;
}
Changing the If Statements To as suggested by nicolas:
public void printPages(double numberToPrint) {
if(tonerLevel == 0) {
System.out.println("Out of toner");
return;
}
if(ammountOfPaper == 0) {
System.out.println("Out of Paper");
return;
}
if(isDoubleSided == false) {
Your if-statements are redundant. You can return directly the boolean value. It saves you 12 lines in your code. For example:
private boolean twoSideNoPaperOdd(double numberToPrint) {
return ((ammountOfPaper - ((int) numberToPrint / 2)) - 1) < 0;
}
There are few conditions repeated often with the same result. Again, it shortens the class by 24 lines.
if (tonerLevel == 0) {
System.out.println("Out of toner");
return; // leave the rest of method
}
if (ammountOfPaper == 0) {
System.out.println("Out of Paper");
return
}
This is the problem :
Input
The first line of input will contain the number of test cases, T (1 ≤ T ≤ 50). Each of the following T
lines contains a positive integer N that is no more than 80 digits in length.
Output
The output of each test case will be a single line containing the smallest palindrome that is greater
than or equal to the input number.
Sample Input
2
42
321
Sample Output
44
323
I keep having time limit exceeded when i submit to the code to online judge ( 3 seconds limit)
class Main {
static String ReadLn (int maxLg)
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
static boolean isPalandriome(String s){
String newString = "";
for(int i =s.length()-1;i >= 0; i--){
newString += s.charAt(i);
}
if(newString.equals(s))
return true;
else
return false;
}
public static void main(String[] args) {
BigInteger entredNumber;
String input;
input = Main.ReadLn(10);
int tests = Integer.parseInt(input);
List<BigInteger> numbers = new ArrayList<BigInteger>();
for (int i =0;i<tests;i++)
{
input = Main.ReadLn(100);
entredNumber = new BigInteger(input);
numbers.add(entredNumber);
}
for(int i=0;i<tests;i++){
BigInteger number = numbers.get(i);
while(!isPalandriome(String.valueOf(number))){
number = number.add(BigInteger.ONE);
}
System.out.println(number);
}
}
}
I can't find what takes too much time in my code.
At last coded Hope you find this helpful took 0.10 seconds
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
CustomReader cr = new CustomReader(1000000);
int T = cr.nextInt(), fIndex, bIndex, fStartIndex, bStartIndex;
StringBuilder output = new StringBuilder();
byte[] input;
boolean isAppend1 = false;
for (int i = 0; i < T; i++) {
input = cr.nextInput();
fStartIndex = bStartIndex = cr.getCurrInputLength() / 2;
isAppend1 = false;
if (cr.getCurrInputLength() % 2 == 0) {
bStartIndex--;
}
fIndex = fStartIndex;
bIndex = bStartIndex;
while (input[bIndex] == input[fIndex]) {
if (bIndex - 1 < 0) {
break;
} else {
bIndex--;
fIndex++;
}
}
if (input[bIndex] > input[fIndex]) {
while (bIndex >= 0) {
input[fIndex++] = input[bIndex--];
}
} else {
if (input[bStartIndex] < 57) {
input[bStartIndex] = (byte) (input[bStartIndex] + 1);
} else {
bIndex = bStartIndex;
while (bIndex >= 0 && input[bIndex] == 57) {
input[bIndex] = 48;
bIndex--;
}
if (bIndex >= 0) {
input[bIndex] = (byte) (input[bIndex] + 1);
} else {
input[0] = 49;
if (fStartIndex != bStartIndex) {
input[fStartIndex] = 48;
bStartIndex = fStartIndex;
} else {
input[fStartIndex + 1] = 48;
bStartIndex = fStartIndex = fStartIndex + 1;
}
isAppend1 = true;
}
}
while (bStartIndex > -1) {
input[fStartIndex++] = input[bStartIndex--];
}
}
for (int j = 0; j < cr.getCurrInputLength(); j++) {
output.append((char) input[j]);
}
if (isAppend1) {
output.append("1");
}
output.append("\n");
}
System.out.print(output.toString());
// genInput();
}
private static class CustomReader {
private byte[] buffer;
private byte[] currInput = new byte[1000000];
private int currInputLength;
private int currIndex;
private int validBytesInBuffer;
CustomReader(int buffSize) {
buffer = new byte[buffSize];
}
public int nextInt() throws IOException {
int value;
byte b;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
break;
}
}
value = b - 48;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
value = (value * 10) + (b - 48);
} else {
break;
}
}
return value;
}
public byte[] nextInput() throws IOException {
byte b;
this.currInputLength = 0;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
break;
}
}
currInput[currInputLength++] = b;
while (true) {
b = getNextByte();
if (b > 47 && b < 58) {
currInput[currInputLength++] = b;
} else {
break;
}
}
return this.currInput;
}
public int getCurrInputLength() {
return this.currInputLength;
}
private byte getNextByte() throws IOException {
if (currIndex == buffer.length || currIndex == validBytesInBuffer) {
validBytesInBuffer = System.in.read(buffer);
currIndex = 0;
}
return buffer[currIndex++];
}
}
public static void genInput() {
for (int i = 0; i < 100; i++) {
System.out.println((int) (Math.random() * 1000000000));
}
}
}
First I want to say thanks for any assistance. I'm relatively new to Java programming. I built a simple TicTacToe game, and I'm having a little trouble.
Every once in a while "X" or "O" will be played twice in a row. I have a boolean variable that is supposed to switch from true to false to change "X" to "O" as each player takes a turn, but for some reason it isn't switching at random times.
I'm thinking it may be a problem with Eclipse or something, because I don't understand why else it would do this.
Below is the code for the game:
public class gameMain {
Boolean player = true;
JPanel gameBoard;
JButton[] b = new JButton[10];
Font font = new Font("Arial", Font.BOLD, 99);
ListenForButtons lfb = new ListenForButtons();
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new gameMain();
}
});
}
public gameMain() {
JFrame j = new JFrame("TicTacToe");
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setLocationRelativeTo(null);
j.setSize(400, 400);
gameBoard = new JPanel();
gameBoard.setLayout(new GridLayout(3, 3));
b[1] = new JButton("");
b[1].addActionListener(lfb);
b[1].setContentAreaFilled(false);
b[1].setFont(font);
b[1].setBorder(BorderFactory.createMatteBorder(0, 0, 2, 2, Color.BLACK));
b[2] = new JButton("");
b[2].addActionListener(lfb);
b[2].setContentAreaFilled(false);
b[2].setFont(font);
b[2].setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, Color.BLACK));
b[3] = new JButton("");
b[3].addActionListener(lfb);
b[3].setContentAreaFilled(false);
b[3].setFont(font);
b[3].setBorder(BorderFactory.createMatteBorder(0, 2, 2, 0, Color.BLACK));
b[4] = new JButton("");
b[4].addActionListener(lfb);
b[4].setContentAreaFilled(false);
b[4].setFont(font);
b[4].setBorder(BorderFactory.createMatteBorder(0, 0, 0, 2, Color.BLACK));
b[5] = new JButton("");
b[5].addActionListener(lfb);
b[5].setContentAreaFilled(false);
b[5].setFont(font);
b[5].setBorder(BorderFactory.createMatteBorder(0, 0, 0, 0, Color.BLACK));
b[6] = new JButton("");
b[6].addActionListener(lfb);
b[6].setContentAreaFilled(false);
b[6].setFont(font);
b[6].setBorder(BorderFactory.createMatteBorder(0, 2, 0, 0, Color.BLACK));
b[7] = new JButton("");
b[7].addActionListener(lfb);
b[7].setContentAreaFilled(false);
b[7].setFont(font);
b[7].setBorder(BorderFactory.createMatteBorder(2, 0, 0, 2, Color.BLACK));
b[8] = new JButton("");
b[8].addActionListener(lfb);
b[8].setContentAreaFilled(false);
b[8].setFont(font);
b[8].setBorder(BorderFactory.createMatteBorder(2, 0, 0, 0, Color.BLACK));
b[9] = new JButton("");
b[9].addActionListener(lfb);
b[9].setContentAreaFilled(false);
b[9].setFont(font);
b[9].setBorder(BorderFactory.createMatteBorder(2, 2, 0, 0, Color.BLACK));
gameBoard.add(b[1]);
gameBoard.add(b[2]);
gameBoard.add(b[3]);
gameBoard.add(b[4]);
gameBoard.add(b[5]);
gameBoard.add(b[6]);
gameBoard.add(b[7]);
gameBoard.add(b[8]);
gameBoard.add(b[9]);
j.add(gameBoard);
j.setVisible(true);
}
public class ListenForButtons implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b[1]) {
setSquare(b[1]);
}
if (e.getSource() == b[2]) {
setSquare(b[2]);
}
if (e.getSource() == b[3]) {
setSquare(b[3]);
}
if (e.getSource() == b[4]) {
setSquare(b[4]);
}
if (e.getSource() == b[5]) {
setSquare(b[5]);
}
if (e.getSource() == b[6]) {
setSquare(b[6]);
}
if (e.getSource() == b[7]) {
setSquare(b[7]);
}
if (e.getSource() == b[8]) {
setSquare(b[8]);
}
if (e.getSource() == b[9]) {
setSquare(b[9]);
}
checkForWin();
}
}
public void setSquare(JButton button) {
if (player) {
button.setText("X");
player = false;
button.removeActionListener(lfb);
} else {
button.setText("O");
player = true;
button.removeActionListener(lfb);
}
}
public void checkForWin() {
if ((b[1].getText().equals("X") && b[2].getText().equals("X") && b[3].getText().equals("X"))
|| (b[4].getText().equals("X") && b[5].getText().equals("X") && b[6].getText().equals("X"))
|| (b[7].getText().equals("X") && b[8].getText().equals("X") && b[9].getText().equals("X"))
|| (b[1].getText().equals("X") && b[4].getText().equals("X") && b[7].getText().equals("X"))
|| (b[2].getText().equals("X") && b[5].getText().equals("X") && b[8].getText().equals("X"))
|| (b[3].getText().equals("X") && b[6].getText().equals("X") && b[9].getText().equals("X"))
|| (b[1].getText().equals("X") && b[5].getText().equals("X") && b[9].getText().equals("X"))
|| (b[3].getText().equals("X") && b[5].getText().equals("X") && b[7].getText().equals("X"))) {
JOptionPane.showMessageDialog(null, "X WINS THE GAME!", "", JOptionPane.INFORMATION_MESSAGE);
resetBoard();
} else if ((b[1].getText().equals("O") && b[2].getText().equals("O") && b[3].getText().equals("O"))
|| (b[4].getText().equals("O") && b[5].getText().equals("O") && b[6].getText().equals("O"))
|| (b[7].getText().equals("O") && b[8].getText().equals("O") && b[9].getText().equals("O"))
|| (b[1].getText().equals("O") && b[4].getText().equals("O") && b[7].getText().equals("O"))
|| (b[2].getText().equals("O") && b[5].getText().equals("O") && b[8].getText().equals("O"))
|| (b[3].getText().equals("O") && b[6].getText().equals("O") && b[9].getText().equals("O"))
|| (b[1].getText().equals("O") && b[5].getText().equals("O") && b[9].getText().equals("O"))
|| (b[3].getText().equals("O") && b[5].getText().equals("O") && b[7].getText().equals("O"))) {
JOptionPane.showMessageDialog(null, "O WINS THE GAME!", "", JOptionPane.INFORMATION_MESSAGE);
resetBoard();
} else if (!b[1].getText().equals("") && !b[2].getText().equals("") && !b[3].getText().equals("")
&& !b[4].getText().equals("") && !b[5].getText().equals("") && !b[6].getText().equals("")
&& !b[7].getText().equals("") && !b[8].getText().equals("") && !b[9].getText().equals("")) {
JOptionPane.showMessageDialog(null, "Cats Game!", "", JOptionPane.INFORMATION_MESSAGE);
resetBoard();
}
}
public void resetBoard() {
for (int i = 1; i <= b.length - 1; i++) {
b[i].setText("");
}
for (int i = 1; i <= b.length - 1; i++) {
b[i].addActionListener(lfb);
}
player = true;
}
}
When ResetBoard() is called and not every button was pressed, then you end up having multiple ActionListeners assigned to those not used buttons.
Here is a example resetBoard() method:
public void resetBoard() {
// Fixed the loop index. Was: (int i = 1; i <= b.length - 1; i++)
for (int i = 0; i < b.length; i++) {
b[i].setText("");
// Adding a listener only if there isn't one already
if (b[i].getActionListeners().length < 1)
b[i].addActionListener(lfb);
}
player = true;
}
As #MadProgrammer suggested i refactored also the setSquare() method:
public void setSquare(JButton button) {
if (player) {
button.setText("X");
} else {
button.setText("O");
}
button.removeActionListener(lfb);
player = !player;
}