I have a method in my project, which randomly selects a button from a list and then writes the given text on it. The problem I am getting is, since it selects the button at random, it writes the text on the button even if there is already a text written on the button. what I want is, for this code to select a button and then check if there is already a text written on it and if there is, then I want it to repeat itself and select another random button, until it finds and write the given text on a button that has no text on it previously.
public class random{
public static String text2 = "text2";
public void static main(String[] args){
JButton button = new JButton("Empty");
JButton button1 = new JButton("Empty");
JButton button2 = new JButton("Empty");
randomButton(button,button1, button2);
}
public void randomButton(JButton button1, JButton button2, JButton button3){
String text = "text";
JButton[] arr = {button1, button2, button3};
Random r = new Random();
JButton b = arr[r.nextInt(arr.length)];
b.setText(text);
b.setEnabled(false);
}
}
The buttons can have one of the three texts on them - Empty, text1 or text2.
What I want to do is, if the button selected at random when the method randomButton is called, I want it to check if the button selected already has text1 or text2 and if it does then I want it to reselect another random button until it finds a button that has Empty written on it and then replace it with text1.
I have tried do while loop, if statement and while loops but it won't work, maybe it because my logic is wrong but i am not sure. below, I have pasted one of my attempts but it does not work.
do {
String text = "text";
JButton[] arr = {button1, button2, button3};
Random r = new Random();
JButton b = arr[r.nextInt(arr.length)];
if (b.getText() != "text" || b.getText() != "text2") {
b.setText(text);
b.setEnabled(false);
} else {
String text = "text";
JButton[] arr = {button1, button2, button3};
Random r = new Random();
JButton b = arr[r.nextInt(arr.length)];
b.setText(text);
b.setEnabled(false);
}
} while (b.getText() == text);