JAVA: Putting alternative ( || ) in loop? - java

I have a quick question. I want to make my code shorter and I'm wondering whether I can put in some way below checkboxes into loop. The sense of this part of code is to enable "Find" button in case when at least one of checkbox is selected. Thank you in advance for every tip.
if (checkBoxes[0].isSelected() == true || checkBoxes[1].isSelected() == true
|| checkBoxes[2].isSelected() == true || checkBoxes[3].isSelected() == true || checkBoxes[4].isSelected() == true
|| checkBoxes[5].isSelected() == true || checkBoxes[6].isSelected() == true || checkBoxes[7].isSelected() == true
|| checkBoxes[8].isSelected() == true || checkBoxes[9].isSelected() == true || checkBoxes[10].isSelected() == true
|| checkBoxes[11].isSelected() == true || checkBoxes[12].isSelected() == true || checkBoxes[13].isSelected() == true
|| checkBoxes[14].isSelected() == true || checkBoxes[15].isSelected() == true || checkBoxes[16].isSelected() == true
|| checkBoxes[17].isSelected() == true || checkBoxes[18].isSelected() == true || checkBoxes[19].isSelected() == true
|| checkBoxes[20].isSelected() == true || checkBoxes[21].isSelected() == true) {
button.setEnabled(true);

Of course you can :
boolean found = false;
for (int i = 0; i < checkBoxes.length && !found; i++) {
found = checkBoxes[i].isSelected();
}
if (found) {
button.setEnabled(true);
}
or you can avoid the boolean variable and break out of the loop when you find the first selected checkbox :
for (int i = 0; i < checkBoxes.length; i++) { // you can also replace this with enhanced
// for loop
if (checkBoxes[i].isSelected()) {
button.setEnabled(true);
break;
}
}

Why not to use stream?
if (Arrays.stream(checkBoxes).anyMatch(checkbox -> checkbox.isSelected())) {
button.setEnabled(true);
}

As you have an array of course you can use a loop.
Here is a version with an enhanced loop :
for (Checkbox checkBox : checkBoxes){
if (checkBox.isSelected()){
button.setEnabled(true);
break;
}
}

try this:
for(int i=0; i < checkBoxes.length; i++) {
if(checkBoxes[i].isSelected()) {
button.setEnabled(true);
break;
}
}

Boolean j = false;
for (byte i = 0; i <= 21)
if (checkBoxes[i].isSelected() == true) {
j = true;
break;
if (j == true) {
//your code
}
you van use this code
it is so easy

Related

The if statement is redundant in Java

I am getting a lightbulb on NetBeans saying "The if statement is redundant"
I want to know how these two are equal to one another
public boolean isVowel(char in)
{
char temp = Character.toLowerCase(in);
if (temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u')
{
return true;
}
else
{
return false;
}
}
and
public boolean isVowel(char in)
{
char temp = Character.toLowerCase(in);
return temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u';
}
I can see how it would return true if one of the vowels matches with temp. However, I am not seeing how it would return false. Would it simply just return false if none of the conditions are met?
Solved: I was looking at the problem the wrong way. For it to return false, each conditional statement would have to be false. Ideally it would return false if the return statement was equivalent to:
return false || false || false || false || false;
and true if any one condition is met
return false || false || false || false || true;
Thanks you guys, it really helped.
The two statements are identical.
int x = #; //user input
if (x==1) { //any condition resulting in a true or false
return true;
} else {
return false;
}
and
return (x==1); //same thing, returning true if true, false if false;
This expression:
(temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u')
calculates a boolean value. An if-statement tests this value. So instead of testing this expression in the ireturning the boolean value in the if/else-clause you can just return it.
Edit you can just prove if your char is a vowel?
Do it this way:
public boolean isVowel(char in) {
return "aeiou".indexOf(Character.toLowerCase(in)) < 0;
}
The two are indeed identical (and the if statement is redundant) and here's why.
The == is an equality operator, which means that, if the left side matches the right side, it evaluates to true, otherwise it evaluates to false. The || is a conditional operator, meaning that, if the equality on the left hand side evaluates to false, it will check the right side to see if it evaluates to true (or, if left side evaluates to true, then the expression will evaluate to true, called short-circuiting). If all of them evaluate to false, then the entire expression will evaluate to false.
Therefore, the if statement as you have it essentially turns into:
if(<expression>==true) { //in the case that the conditional evaluates to true
return true;
}
else { //in the case the conditional evaluates to false
return false;
}
So, that can just be reduced down to expression, since it will evaluate to a boolean anyways.
return <expression> //will be true if true, false if false
There's more on this in the Oracle documentation
boolean isNumeric(char cc){
//begin // test if cc is numeric
return (
(cc == '0')
| (cc == '1')
| (cc == '2')
| (cc == '3')
| (cc == '4')
| (cc == '5')
| (cc == '6')
| (cc == '7')
| (cc == '8')
| (cc == '9') );
} // isNumeric

Java Tic Tac Toe AI not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
My AI code for a computer player is not working as expected. I want it to play a random move, but block an opponent's incoming winning turn. However, it sometimes stops working altogether, and other times plays a specific move even though there is no incoming win combo. My computer AI code is below.
public void compturn()
{
count++ ;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
if (b1.getText() == b2.getText() && b2.getText() != "" && b3.getText() == "")
{
b3.setText(letter);
b3bool = false ;
}
else if (b4.getText() == b5.getText() && b6.getText() == "")
{
b6.setText(letter);
b6bool = false ;
}
else if (b7.getText() == b8.getText() && b9.getText() == "")
{
b9.setText(letter);
b9bool = false ;
}
else if (b1.getText() == b4.getText() && b4.getText() != "" && b7.getText() == "")
{
b7.setText(letter);
b7bool = false ;
}
else if (b2.getText() == b5.getText() && b8.getText() == "")
{
b8.setText(letter);
b8bool = false ;
}
else if (b3.getText() == b6.getText() && b9.getText() == "")
{
b9.setText(letter);
b9bool = false ;
}
else if (b1.getText() == b5.getText() && b5.getText() != "" && b9.getText() == "")
{
b9.setText(letter) ;
b9bool = false ;
}
else if (b3.getText() == b5.getText() && b7.getText() == "")
{
b7.setText(letter);
b7bool = false ;
}
else
{
randomMove();
}
}
public void randomMove()
{
int randomnum = (int)(Math.random() * 10);
if(randomnum == 1 )
{
if(b1.getText().equals("X") || b1.getText().equals("O"))
{
randomMove();
}
else
{
b1.setText(letter);
}
}
if(randomnum == 2 )
{
if(b2.getText().equals("X") || b2.getText().equals("O"))
{
randomMove();
}
else
{
b2.setText(letter);
}
}
if(randomnum == 3 )
{
if(b3.getText().equals("X") || b3.getText().equals("O"))
{
randomMove();
}
else
{
b3.setText(letter);
}
}
if(randomnum == 4 )
{
if(b4.getText().equals("X") || b4.getText().equals("O"))
{
randomMove();
}
else
{
b4.setText(letter);
}
}
if(randomnum == 5 )
{
if(b5.getText().equals("X") || b5.getText().equals("O"))
{
randomMove();
}
else
{
b5.setText(letter);
}
}
if(randomnum == 6 )
{
if(b6.getText().equals("X") || b6.getText().equals("O"))
{
randomMove();
}
else
{
b6.setText(letter);
}
}
if(randomnum == 7 )
{
if(b7.getText().equals("X") || b7.getText().equals("O"))
{
randomMove();
}
else
{
b7.setText(letter);
}
}
if(randomnum == 8 )
{
if(b8.getText().equals("X") || b8.getText().equals("O"))
{
randomMove();
}
else
{
b8.setText(letter);
}
}
if(randomnum == 9 )
{
if(b9.getText().equals("X") || b9.getText().equals("O"))
{
randomMove();
}
else
{
b9.setText(letter);
}
}
}
And my complete code for the main game is here
public int oneplayergame()
{
// ----=---------------------- CREATING ALL JBUTTONS ON THE GAME SCREEN AND ADDING ACTION LISTENERS AND REACTIONS -----------------------------------------
b1 = new JButton("");
b1.setToolTipText("Mark this box");
b1.setFont(TToeFont);
b1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b1bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b1.setText(letter);
b1bool = false ;
calculatevictory();
compturn();
processturn();
}}});
b2 = new JButton("");
b2.setFont(TToeFont);
b2.setToolTipText("Mark this box");
b2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b2bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b2.setText(letter);
b2bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b3 = new JButton("");
b3.setToolTipText("Mark this box");
b3.setFont(TToeFont);
b3.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b3bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b3.setText(letter);
b3bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b4 = new JButton("");
b4.setToolTipText("Mark this box");
b4.setFont(TToeFont);
b4.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b4bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b4.setText(letter);
b4bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b5 = new JButton("");
b5.setToolTipText("Mark this box");
b5.setFont(TToeFont);
b5.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b5bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b5.setText(letter);
b5bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b6 = new JButton("");
b6.setToolTipText("Mark this box");
b6.setFont(TToeFont);
b6.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b6bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b6.setText(letter);
b6bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b7 = new JButton("");
b7.setToolTipText("Mark this box");
b7.setFont(TToeFont);
b7.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b7bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b7.setText(letter);
b7bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b8 = new JButton("");
b8.setToolTipText("Mark this box");
b8.setFont(TToeFont);
b8.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b8bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b8.setText(letter);
b8bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b9 = new JButton("");
b9.setToolTipText("Mark this box");
b9.setFont(TToeFont);
b9.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b9bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b9.setText(letter);
b9bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
//CREATING GAME SCREEN LAYOUT
//CREAING GAME SCREEN CONTENT PANE AND ADDING BUTTONS TO IT
// This method checks if someone won the game every time you click a button
public void calculatevictory(){
if (b1.getText() == b2.getText() && b2.getText() == b3.getText() && b1.getText() != "")
{
win = true ;
}
else if (b4.getText() == b5.getText() && b5.getText() == b6.getText() && b4.getText() != "")
{
win = true ;
}
else if (b7.getText() == b8.getText() && b8.getText() == b9.getText() && b7.getText() != "")
{
win = true ;
}
else if (b1.getText() == b4.getText() && b4.getText() == b7.getText() && b1.getText() != "")
{
win = true ;
}
else if (b2.getText() == b5.getText() && b5.getText() == b8.getText() && b2.getText() != "")
{
win = true ;
}
else if (b3.getText() == b6.getText() && b6.getText() == b9.getText() && b3.getText() != "")
{
win = true ;
}
else if (b1.getText() == b5.getText() && b5.getText() == b9.getText() && b1.getText() != "")
{
win = true ;
}
else if (b3.getText() == b5.getText() && b5.getText() == b7.getText() && b3.getText() != "")
{
win = true ;
}
else
{
win = false ;
}
}
// This method sends the win message
public void processturn()
}
// This method resets all game variables
public void resetgame()
{
count = 1 ;
b1bool = true ;
b2bool = true ;
b3bool = true ;
b4bool = true ;
b5bool = true ;
b6bool = true ;
b7bool = true ;
b8bool = true ;
b9bool = true ;
win = false ;
gameinit = true ;
b1.setText("");
b2.setText("");
b3.setText("");
b4.setText("");
b5.setText("");
b6.setText("");
b7.setText("");
b8.setText("");
b9.setText("");
}
public void compturn()
{
}
public void randomMove()
{
}
}
Welcome to AI... there are numerous ways you can do this. I'll give you a few tips.
I assume count is used to determine who's turn it is. I'd suggest you rather create an integer 'turn' and then simply do this:
turn = 1 -turn
...where you currently increment count. If it's 0 than it's o's turn, else x's. You can then remove those two long if statements. (You can also use a boolean flag and just not it each time, like so turn = !turn.)
Now the rest... I see you have no arrays. Are you comfortable using them?
If so, rather define, winning sequences. For example:
int[][] win = new int[][]{{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, ...}
Then all you do to determine if you can win, go is to see if you have two of your tokens in spot win[i][0], win[i][1] or win[i][2]. If the third spot it empty, you can win and should move there,
If you can't win, repeat the above process to defend.
If you do not have to defend and you cannot win, move in the centre. If the centre is taken, take a corner, else move random.
This will give you an AI that can still lose sometimes, but will show some intelligence. If you really want to build something unbeatable have a look at the minimax search algorithm.
Good luck!

this method must return a result of type boolean, java

public boolean Winner() {
for (int z = 0; z < 3; z++) {
if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]
) {
return true;
}
}
for(int i=0; i<7;i+=3){
if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {
return true;}
}
}
It returns me this error: this method must return a result of type boolean. What am I doing wrong?
Right now, the function isn't guaranteed to return a boolean, because it's possible that neither of the if statements will ever be entered.
You could fix it like this (but only do this if it's actually what your logic needs!):
public boolean Winner() {
for (int z = 0; z < 3; z++) {
if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]
) {
return true;
}
}
for(int i=0; i<7;i+=3){
if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {
return true;}
}
return false;
}
The Java compiler doesn't make assumptions that a for loop will have an iteration or that an if statement block will run.
There are execution paths where there is no return statement. What happens if the execution path doesn't execute any of the existing return statements and drops to the bottom? There isn't a return there.
Add a return at the bottom.
All possible ways that the method can exit need to return something. If your code makes it through both for loops without having an if condition evaluate to true, then you need a return at the end that specifies what gets returned.
The compiler is not aware that at least one of the loops will be executed. It takes into account all the possibilities of the execution and one of them is that neither of the loops will be executed and in that case there is no return statement. So insert a return statement out of the loops as well.
The answer to this question is easy. It happened to me too. The problem in your code is that you don't say to the computer what to do in case that the "if" statement is wrong, so you just have to add an "else {return false}" to every "if". Another tip is: please make your code cleaner and readable.
public boolean Winner() {
for (int z = 0; z < 3; z++) {
if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]) {
return true;
} else {
return false;
}
}
for (int i=0; i<7; i+=3) {
if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {
return true;
} else {
return false;
}
}
}

Checking string for large amount of different, incremental values

Currently I am checking a string for the following:
if(parseCommand.contains("vlan1")
|| parseCommand.contains("Fa0/1i") || parseCommand.contains("Fa0/1o")
|| parseCommand.contains("Fa1/0") || parseCommand.contains("Fa1/1")
|| parseCommand.contains("Fa1/2") || parseCommand.contains("Fa1/3")
|| parseCommand.contains("Fa1/4") || parseCommand.contains("Fa1/5")
|| parseCommand.contains("Fa1/6") || parseCommand.contains("Fa1/7")
|| parseCommand.contains("Fa1/8") || parseCommand.contains("Fa1/9")
|| parseCommand.contains("Fa1/11") || parseCommand.contains("Gi0"))
{
//do things here
}
However it may contain vlan1 up to vlan4094 and i have to check for these. What is the simplest way to do this, do I have to stick it all in a for loop incrementing to 4094 I guess?
for (int i = 1; i <= 4094; i++)
{
if(parseCommand.contains("vlan"[i]))
{
//do stuff here
}
}
if(other conditions from above)
{
//do same stuff again here
}
Or else I could stick all the conditions in the for loop and do everything inside there. This all seems messy, is there a non-messy way of doing it?
I think this regex should do it:
String parseCommand = "vlan4094";
if (parseCommand.matches(".*?vlan([1-3][0-9]{3}|" +
"[1-9][0-9]{0,2}|" +
"40(9[0-4]|[0-8][0-9])).*"))
System.out.println("matches");
[1-3][0-9]{3} - 1000-3999
[1-9][0-9]{0,2} - 1-999
9[0-4] - 90-94
[0-8][0-9] - 00-89
40(9[0-4]|[0-8][0-9]) - 4000-4094
Something like this is probably simpler:
String parseCommand = "vlan4094";
if (parseCommand.startsWith("vlan"))
{
int v = Integer.parseInt(parseCommand.substring(4));
if (v >= 1 && v <= 4094)
/* do stuff */
}
Suggested change:
Replace:
parseCommand.contains("Fa1/0") || parseCommand.contains("Fa1/1")
|| parseCommand.contains("Fa1/2") || parseCommand.contains("Fa1/3")
|| parseCommand.contains("Fa1/4") || parseCommand.contains("Fa1/5")
|| parseCommand.contains("Fa1/6") || parseCommand.contains("Fa1/7")
|| parseCommand.contains("Fa1/8") || parseCommand.contains("Fa1/9")
with
parseCommand.matches(".*?Fa1/[0-9].*")
You can combie them into one boolean
boolean b = false;
for(int i = 1 ; i < 4094 ; i ++){
b = b || parseCommand.contains("vlan" + i);
}
Then check your boolean value
If the only problem is with "vlanXXX" you can remove the "vlan" part of the string:
parseCommand = parseCommand.replaceFirst("vlan", "");
and then cast it to int
int value = Integer.parseInt(parseCommand);
and then comparing this result with that whaat you want
if((value >= 1) && (value <= 4094)){....}
This will only work for the given case and you have to handle the case where parseCommand cannot be cast to int. And it is much more understandable than using whatever regular expresion

Hexadecimal Validation Algorithm

I'm trying to validate a hexadecimal number and its not going too well. I'm trying the code below but my logic isn't exactly on the ball. Any help?
if (!array[i].equals("A") || !array[i].equals("B") || !array[i].equals("C") || !array[i].equals("D") || !array[i].equals("E") || !array[i].equals("F"))
{
b[i] = false;
}
else
{
b[i] = true;
}
The aim of the above code is to give me a true or false value. True being the value is between A to F false being the value isn't between A to F.
if ((array[i]-'A') > 5)
b[i]=false;
else
b[i]=true;
Change all || to &&.
Right now your if condition always evaluates to true (since any string is not equal to either "A" or "B").
Alternatively, replace the whole construct with:
b[i] = array[i].equals("A") || array[i].equals("B") || array[i].equals("C") ||
array[i].equals("D") || array[i].equals("E") || array[i].equals("F");
if (array[i].equals("A") || array[i].equals("B") || array[i].equals("C") || array[i].equals("D") || array[i].equals("E") || array[i].equals("F"))
{ b[i] = true; }
else
{ b[i] = false; }
alternatively you could use a List and use .contains() as well.
List<String> hexchars = new ArrayList<String>();
hexchars.add("A");
hexchars.add("B");
hexchars.add("C");
hexchars.add("D");
hexchars.add("E");
hexchars.add("F");
return hexchars.contains("A");
But a regular expression would be the cleanest way to do this in the long run.

Categories

Resources