Java – check if string x is equal to any string in string []
•
Java
If the string entered by the user is equal to any string in the string array, I try to set a Boolean value of true
I improvised and asked this question
String[] cancelWords = {"cancel","nevermind","scratch that"}; boolean valueEqualsCancel = true; for(String cancelWord : cancelWords) { if(!valueEqualsCancel) break; valueEqualsCancel = valueEqualsCancel && value.equals(cancelWord); }
But valueequalscancel will never be true
Do you have a tip?
Solution
Valueequalscancel will never be true because you won't exit the loop when you find cancelword
To achieve the break statement, you need to set valueequalscancel to false
For example, if you search for "Cancel" after the first loop, the variable valueequalscancel is:
valueEqualsCancel = valueEqualsCancel && value.equals(cancelWord) = TRUE && TRUE = TRUE;
So you won't break in the second cycle Then evaluate the expression again
valueEqualsCancel = valueEqualsCancel && value.equals(cancelWord) = TRUE && FALSE = FALSE;
Therefore, in the third loop, you will exit and valueequalscancel is false
You can correct the code by:
String[] cancelWords = {"cancel","scratch that"}; boolean found = false; for(String cancelWord : cancelWords) { found = value.equals(cancelWord); if (found) break; }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码