I want the following if statement to compare against multiple strings but when i compare against more than one it gives me the error message that I created. Below is the code which does not work.
The variables are test = 'c3400553' and test2 = 'c3400554'
if (!uname.getText().toString().matches("[cC][0-9]{7}") ||
!uname.getText().toString().equals(test) ||
!uname.getText().toString().equals(test2)
) {
uname.setError("Incorrect ID Format");
}
Below is the code which works for one comparison.
String test = "c3400553";
...
if (!uname.getText().toString().matches("[cC][0-9]{7}") ||
!uname.getText().toString().equals(test)
) {
uname.setError("Incorrect ID Format" );
}
I don't understand what the issue is
That's because you either need to remove some !, or you need to replace your || by &&.
It depends on what you are trying to achieve. If you want the id to be declared incorrect if it doesn't match the format AND if it is not equal to test AND ALSO not equal to test2, then the solution is this :
if (!uname.getText().toString().matches("[cC][0-9]{7}") &&
!uname.getText().toString().equals(test) &&
!uname.getText().toString().equals(test2) ) {
uname.setError("Incorrect ID Format" );
}
Otherwise, if what you want to do is to check whether uname matches the format, and is NOT equal to test and test2, then the problem is that you need to remove the ! before comparisons with test and test2 :
if (!uname.getText().toString().matches("[cC][0-9]{7}") ||
uname.getText().toString().equals(test) ||
uname.getText().toString().equals(test2) ) {
uname.setError("Incorrect ID Format" );
}
Related
I'm trying to make simple if statement , I need to see if my two String's values are not empty (does not equal "").
I use && operator , but sadly , it only checks one string properly if it's not empty , and if the second string is empty, he passes . Making && kinda useless for me.
if ( StringUtils.isNullOrEmpty(name) && StringUtils.isNullOrEmpty(sname)
) {do something}
I need them both to be checked properly . If at least one string is empty return false .
If both are not empty return true.
Currently your condition is true if both Strings are null or empty.
If you want both not to be null or empty you need :
if ( !StringUtils.isNullOrEmpty(name) && !StringUtils.isNullOrEmpty(sname)
) {do something}
&& is smart and if first condition is false it doesn't try the second.
use & could achieve what you want.
The problem is that your check is wrong. You want it to only pass if both ARE empty.
So you should go for
if ( !StringUtils.isNullOrEmpty(name) && !StringUtils.isNullOrEmpty(sname)
) {do something}
or if u want to catch it in the if statement if one of them IS empty, you should use or:
if ( StringUtils.isNullOrEmpty(name)|| StringUtils.isNullOrEmpty(sname)
) {do something}
isNullOrEmpty will return true if name is empty, but you want it NOT empty, so negate the conditions using !.
if ( !StringUtils.isNullOrEmpty(name) && !StringUtils.isNullOrEmpty(sname)
) {do something}
Another alternative is:
if (!(StringUtils.isNullOrEmpty(name) || StringUtils.isNullOrEmpty(sname)
)) {do something}
However, the above is not a recommended coding style, as it is difficult to catch the ! hidden just before the line, and code readers may get confused.
About || and && operators optimized checking:
|| checks for the first true condition from left to right and skips any further checking if it finds one true condition.
&& checks for the first false condition from left to right and skips any further checking if it finds one false condition.
At first it didn't looked any sense to me , and it didn't worked . Only then I realized that I need to to flip the return statements.
if (!StringUtils.isNullOrEmpty(name) && !StringUtils.isNullOrEmpty(sname)) {
System.out.println("ok");
return true;}
else {
System.out.println("empty names");
return false;
}
Now it seems to work just fine.
Using '&' as logical operator you can do the following thing. Here we have not use StringUtils -
if( ( null!=name && !name.isEmpty() ) &
( null!=sname && !sname.isEmpty() ) ){do something}
so I'm trying to figure out how to create a condition for my decision structure. I'm making a program that converts military time to conventional time. When times are entered, they must be in a XX:XX format, where X equals a digit. I'm wondering, how can I make a validation that checks to make sure that ":" always exists as a colon and is in the same spot?
myString.charAt(5) == ':'
Just change 5 to whatever you need, and check string length before you do this, so you don't ask for something past the end of a short string.
You could search the string with indexOf(), which returns the index at which the character is found. This will check if a colon is in the string and if it's in the right position.
if("10:00".indexOf(':') == 2)
// do something
It will return -1 if the value is not found. Check out the java documentation for more information.
Here is the answer for it
Suppose you had string that contains XX:XX
yourString="XX:XX"
yourString.contains(":") - return true - if exists
":" takes the 3rd position. So it will be 2(0,1,2)
yourString.charAt(2) == ':'
Together , it will be
if(yourString.contains(":") && yourString.charAt(2) == ':'){
//your logic here
}else{
something here
}
Here is one approach to that,
String[] test = new String[] { "00:00", "NN:NN", "12,13", "12:13" };
for (String fmt : test) {
boolean isValid = true;
for (int i = 0; i < fmt.length(); i++) {
char c = fmt.charAt(i);
if (i == 2) {
if (c != ':') { // here is the colon check.
isValid = false;
break;
}
} else {
// This checks for digits!
if (!Character.isDigit(c)) {
isValid = false;
break;
}
}
}
System.out.println(fmt + " is " + isValid);
}
Output is
00:00 is true
NN:NN is false
12,13 is false
12:13 is true
#WillBro posted a good answer but I give you another option:
myString.indexOf(":") == 5
With indexOf you can also look for full String inside a String.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
But for string format validations I suggest you to use Regular Expresions.
Here's a full example that does what you want to do:
http://www.mkyong.com/regular-expressions/how-to-validate-time-in-24-hours-format-with-regular-expression/
So, I'm rather new to Java and I just starting a project, but I ran into some issues.
My question is... How do I link a user input (argument) with a String?
I have already defined a few Strings earlier on in my code, but in this line I want it to match up and check from the String which matches the argument and check if it contains something:
if (!cs.hasPermission("foo." + args[0]) && [CODE HERE] ){
I want [CODE HERE] to check If args[0] (user input) matches a String, if it does then check if it matches some text.
Java has a .equals() method which can be used to compare two Strings. It can used to compare two variables which hold references to String objects or to compare String literals
if( args[0].equals(someString) ) { // compare args[0] to another String variable
}
if( "someText".equals(args[0]) ) { // compare args[0] to a String literal
}
Reading through the String documentation will also be very useful to you starting out.
This is String equals api, so it should look something like:
if (!cs.hasPermission("foo." + args[0]) && args[0].equals(string){
//code
}
You can easily do it with the equals() method. But you should also check that args[0] is set.
if (args.length > 0) {
if (!cs.hasPermission("foo." + args[0]) && "StringToCompare".equals(args[0])) {
// do something
}
} else {
// handle error
}
Is it possible to have multiple arguments for a .contains? I am searching an array to ensure that each string contains one of several characters. I've hunted all over the web, but found nothing useful.
for(String s : fileContents) {
if(!s.contains(syntax1) && !s.contains(syntax2)) {
found.add(s);
}
}
for (String s : found) {
System.out.println(s); // print array to cmd
JOptionPane.showMessageDialog(null, "Note: Syntax errors found.");
}
How can I do this with multiple arguments? I've also tried a bunch of ||s on their own, but that doesn't seem to work either.
No, it can't have multiple arguments, but the || should work.
!s.contains(syntax1+"") || !s.contains(syntax2+"") means s doesn't contain syntax1 or it doesn't contain syntax2.
This is just a guess but you might want s contains either of the two:
s.contains(syntax1+"") || s.contains(syntax2+"")
or maybe s contains both:
s.contains(syntax1+"") && s.contains(syntax2+"")
or maybe s contains neither of the two:
!s.contains(syntax1+"") && !s.contains(syntax2+"")
If syntax1 and syntax2 are already strings, you don't need the +""'s.
I believe s.contains("") should always return true, so you can remove it.
It seems that what you described can be done with a regular expression.
In regular expression, the operator | marks you need to match one of several choices.
For example, the regex (a|b) means a or b.
The regex ".*(a|b).*" means a string that contains a or b, and other then that - all is OK (it assumes one line string, but that can be dealt with easily as well if needed).
Code example:
String s = "abc";
System.out.println(s.matches(".*(a|d).*"));
s = "abcd";
System.out.println(s.matches(".*(a|d).*"));
s = "fgh";
System.out.println(s.matches(".*(a|d).*"));
Regular Exprsssions is a powerful tool that I recommend learning. Have a look at this tutorial, you might find it helpful.
There is not such thing as multiple contains.
if you require to validate that a list of string is included in some other string you must iterate through them all and check.
public static boolean containsAll(String input, String... items) {
if(input == null) throw new IllegalArgumentException("Input must not be null"); // We validate the input
if(input.length() == 0) {
return items.length == 0; // if empty contains nothing then true, else false
}
boolean result = true;
for(String item : items) {
result = result && input.contains(item);
}
return result;
}
I am using a program to read keywords in a file and sort them on basis of frequency. I am using Map data structure for the same.
But i am facing problem, even if i have repeated entries, their count is not increased. Thus if a word is repeated in the file it is stored in a different place in the data structure rather than incrementing value of the previous entry in the maps. Please find my code below. That is what i tried. Also i am making sure if a match is "" or " " it is not stored in the hash map still it is counted.
Pattern p = Pattern.compile("[a-zA-Z]*",Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(handlerContent);
while(m.find() ) //&& (m.group().length()>1)
{
boolean blnExists = keyword_counts.containsValue(m.group());
if(blnExists==true)
{
if(m.group()!="" || m.group()!=" ")
{
System.out.println("Repeat");
keyword_counts.put(m.group(), keyword_counts.get(m.group()+1));
System.out.println(m.group()+" "+keyword_counts.get(m.group()) );
}
}
else
{
if(m.group()!="" || m.group()!=" ")
{
keyword_counts.put(m.group(), 1);
System.out.println(m.group()+" "+keyword_counts.get(m.group()) );
}
}
}
Your test should probably be:
keyword_counts.containsKey(m.group());
And you should use equals to compare strings instead of == or != but that is not the reason for your issue.
in Java "=" should not be used with strings. use the "equals" method instead.
in your statement boolean blnExists = keyword_counts.containsValue(m.group());
you are check for the value instead of the key.
try this:
boolean blnExists = keyword_counts.containsKey(m.group());
and use if(m.group() != null && !"".equals(m.group().trim())) instead of
if(m.group()!="" || m.group()!=" ")