My Object returns me - from
Log.d("FormattedDate", Object.getDOB());
if (!Object.getDOB().matches("[^-]*")) {
txtDOB.setText(Object.getDOB());
} else {
txtDOB.setText("-");
}
I am checking if my Object.getDOB() matches with -, then show emptry strings, but this regExp is not working.
java.lang.String has a String#contains() method that does this for you:
Returns true if and only if this string contains the specified
sequence of char values.
if (Object.getDOB().contains("-")) {
//code
}
You could also use
if (Object.getDOB().indexOf("-") != -1) {
//code
}
if it returns -1 then the string does not contain the char (in your case "-"). Otherwise it returns the index of the char.
You can use contains() in java to search which is available in String class
Returns true if and only if this string contains the specified
sequence of char values.
getDOB().contains("-")
SEE HERE
Related
I'm trying to write a method that checks if a given string only contains these {([])} characters.
// Test strings
String S = "{U}" // should give FALSE
String S = "[U]" // should give FALSE
String S = "U" // should give FALSE
String S = "([)()]" // should give TRUE
I've tried:
if(S.matches("[{(\\[\\])}]")) {
return 1;
}
But this returns never true.
String.matches() matches the entire string against the pattern. The pattern you are trying is failing because it only matches a single character - for example, "{".matches("[{(\\[\\])}]") would return true. You need to add a repeat to your regex - either * if you want to match empty strings, or + if the string must contain at least one character, like so:
if(S.matches("[{(\\[\\])}]+")) {
return 1;
}
if(S.matches("^[{(\\[\\])}]+$")) {
return 1;
}
^ - beginning of the line
[]+ - characters contained in character class [] ONE OR MORE times
$ - end of the line
If you want to create a method (as you've mentioned in question), you might want to consider creating such method returning boolean (note that returning boolean (true or false) is not equal to returning 1 or 0 in Java):
public boolean checkIfContainsOnlyParenthesis(String input) {
return input.matches("^[{(\\[\\])}]+$");
}
If your intention was to return 1 when condition is fulfilled and - for example - 0, when it's not, you need to change return value of that method toint:
public int checkIfContainsOnlyParenthesis(String input) {
if(input.matches("^[{(\\[\\])}]+$")) {
return 1;
} else {
return 0;
}
}
That way you can pass your S string as argument of that method like this:
checkIfContainsOnlyParenthesis(S);
I'm trying to check if a letter submitted by user is contained in a string, but it always return false. From what I read the .equals() function should work. I was expecting that if a user inputs the letter "a" it would return "pass" if the string was "america".
for (int i = 0; i < outputTest.length(); i++){
if (userInput.equals(outputTest.charAt(i))){
System.out.println("Pass");
}else {
System.out.println("Fail");
}
}
Based on outputTest.length() and outputTest.charAt() I am assuming that outputTest is String.
Based on userInput.equals I am assuming it is not primitive type like char (since primitive types don't have methods). It is also not Character, otherwise you would see Pass few times. So it most likely is also String.
outputTest.charAt(i) returns char, but you are comparing it with String which equals method looks like:
964 public boolean equals(Object anObject) {965 if (this == anObject) {966 return true;967 }968 if (anObject instanceof String) {969 String anotherString = (String)anObject;970 int n = value.length;971 if (n == anotherString.value.length) {972 char v1[] = value;973 char v2[] = anotherString.value;974 int i = 0;975 while (n-- != 0) {976 if (v1[i] != v2[i])977 return false;978 i++;979 }980 return true;981 }982 }983 return false;984 }
So since equals expects Object, char (returned from outputTest.charAt(i)) will be automatically boxed to Character, but since Character doesn't extend String test
if (anObject instanceof String)
will fail and you will immediately move to return false;.
You may want to use contains method if you want to check if one String contains another
outputTest.contains(userInput)
To find a string in another string, just do:
return text.contains(string);
To find a char in a string, do
return text.indexOf(ch) > -1;
What is the data type of your object userInput? You seem to be comparing a String object with a character which is returned by the charAt() method. That will always return false.
When you are learning to use methods, a good habit to develop is to look at what kind of data type the methods apply or return. For instance, you cannot code this: char scanner.nextLine() // nextLine() is to read String, not char. Therefore, in your code outputTest.charAt(i) // I am a char, and this userInput.equals() // I am a String, you are comparing different things. You cannot compare an apple with a desk because they are two different objects. The compiler will always tell you false.
I assume: String inputTest = scanner.nextLine(); for user input a letter, and you can consider "a" as a String with a length 1. (or any other letters inside)
if (outputTest.contains(userInput)) // now you are comparing String and String
System.out.println("Pass");
else
System.out.println("Fail");
The constructor will throw an IllegalArgumentException exception with the message "Invalid Address Argument" if any parameter is null, or if the zip code has characters others than digits.
The method Character.isDigit can help during the implementation of this method. See the Java API (Character class) for additional information.
I've had the illegal argument exception down. But, not the zip code. Help?
Program.
if(street==null||city==null||state==null){
throw new IllegalArgumentException("Invalid Address Argument");
}
if(zip == Character.isDigit(ch)){
//To do???
}
try apache stringutils
public static boolean isNumeric(CharSequence cs)
Checks if the CharSequence contains only Unicode digits. A decimal point is not a Unicode digit and returns false.
null will return false. An empty CharSequence (length()=0) will return false.
StringUtils.isNumeric(null) = false
StringUtils.isNumeric("") = false
StringUtils.isNumeric(" ") = false
StringUtils.isNumeric("123") = true
StringUtils.isNumeric("12 3") = false
StringUtils.isNumeric("ab2c") = false
StringUtils.isNumeric("12-3") = false
StringUtils.isNumeric("12.3") = false
Parameters:
cs - the CharSequence to check, may be null
Returns:
true if only contains digits, and is non-null
Since:
3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence), 3.0 Changed "" to return false and not true
int zipcode = 0;
try {
zipcode = Integer.parseInt(zipcode);
}catch (Exception e){}
if (zipcode <= 0)
{
throw new Exception(..);
}
And less than 1,000,000 if you want to be precise. You are using Char which makes no sense as you will have a String.
This sounds like homework to me, so I think the first thing you need to do here is learn how to read the documentation. Let's start by taking your instructor's hint, and looking up the documentation for Character.isDigit(char ch)
public static boolean isDigit(char ch)
Handwaving away some of the terms there, the critical things are that the method is static (which means we call it like Character.isDigit(myVariable) and that it returns a boolean (true or false value), and that it accepts a parameter of type char.
So, to call this method, we need a char (single character). I'm assuming that your zip variable is a String. We know that a string is made up of multiple characters. So what we need is a way to get those characters, one at a time, from the String. You can find the documentation for the String class here.
There's a couple of ways to go about it. We could get the characters in an array using toCharArray(), or get a specific character out of the string using charAt(int index)
However you want to tackle it, you need to do this (in pseudocode)
for each char ch in zip
if ch is not a digit
throw new IllegalArgumentException("Invalid Address Argument")
I have a simple string that I'm trying to determine if a specific index results in a specific char.
I'm trying to do it like this (but I get compilation errors):
if(myString.charAt(7).equals("/")) {
// do stuff
} else {
// do other stuff
}
Error:
Type mismatch: cannot convert from char to boolean
(myString.charAt(7).equals("/")
should be following because charAt() returns char:
myString.charAt(7) == '/'
if(myString.charAt(7)== '/') {
// do stuff
} else {
// do other stuff
}
Putting a character in double quotes makes it a String. Single quotes makes it a char. And you compare characters with literal == whereas you compare Objects with the equals method
There's a couple solutions on this answer that give you what you were probably trying to do, which is compare a single character to another single character. I won't go over that because they've done excellently.
But you can still use a String if you like, and prepare for the future. (Perhaps "/" changes to "//"?) you can do this:
if(myString.substring(7,8).equals("/")) {
// stuff
}
Then down the road you might be like
public static final String SEPARATOR_STRING = "//";
public static final int SEPARATOR_START = 7;
public static final int SEPARATOR_END = 7 + SEPARATOR_STRING.length();
// later
if(myString.substring(SEPARATOR_START,7SEPARATOR_END).equals(SEPARATOR_STRING)) {
// stuff
}
charAt() returns char, not object, so you need to compare it that way:
if(myString.charAt(7)== '/') {
...
note the single quote around /.
if(myString.substring(7,8).equals("/"))
or
if(myString.charAt(7)=='/')
or
if(myString.indexOf("/"))==7) can be use
I have this code which searches a string array and returns the result if the input string matches the 1st characters of a string:
for (int i = 0; i < countryCode.length; i++) {
if (textlength <= countryCode[i].length()) {
if (etsearch
.getText()
.toString()
.equalsIgnoreCase(
(String) countryCode[i].subSequence(0,
textlength))) {
text_sort.add(countryCode[i]);
image_sort.add(flag[i]);
condition_sort.add(condition[i]);
}
}
}
But i want to get those string also where the input string matches not only in the first characters but also any where in the string? How to do this?
You have three way to search if an string contain substring or not:
String string = "Test, I am Adam";
// Anywhere in string
b = string.indexOf("I am") > 0; // true if contains
// Anywhere in string
b = string.matches("(?i).*i am.*"); // true if contains but ignore case
// Anywhere in string
b = string.contains("AA") ; // true if contains but ignore case
I have not enough 'reputation points' to reply in the comments, but there is an error in the accepted answer. indexOf() returns -1 when it cannot find the substring, so it should be:
b = string.indexOf("I am") >= 0;
Check out the contains(CharSequence) method
Try this-
etsearch.getText().toString().contains((String) countryCode[i]);
You could use contains. As in:
myString.contains("xxx");
See also: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html, specifically the contains area.
Use the following:
public boolean contains (CharSequence cs)
Since: API Level 1
Determines if this String contains the sequence of characters in the CharSequence passed.
Parameters
cs the character sequence to search for.
Returns
true if the sequence of characters are contained in this string, otherwise false
Actually, the default Arrayadapter class in android only seems to search from the beginning of whole words but by using the custom Arrayadapter class, you can search for parts of the arbitrary string. I have created the whole custom class and released the library. It is very easy to use. You can check the implementation and usage from here or by clicking on the link provided below.
https://github.com/mohitjha727/Advanced-Search-Filter
You can refer to this simple example-
We have names " Mohit " and "Rohan" and if We put " M" only then Mohit shows up in search result, but when we put "oh" then both Mohit and Rohan show up as they have the common letter 'oh'.
Thank You.