How to verify if a string contains a whole other string? - java

So I have this method which returns true if the validation is correct:
private boolean validation() {
String emailStr = etEmail.getText().toString();
if (emailStr.trim().isEmpty()) {
etEmail.setError(getResources().getString(R.string.eroareEmpty));
return false;
} else if (!emailStr.endsWith("stud.ase.ro") && emailStr.length() <= 15) {
etEmail.setError(getResources().getString(R.string.eroareEmail));
return false;
}
return true;
}
I want to verify that the text i type in EditText etEmail contains (only at the end of the string) "stud.ase.ro", the whole string not just a part of it.
In simple words, i want to verify if the email ends with "stud.ase.ro" and nothing else.
Currently my method returns true, even if i type something unsual like "hellllllllllllooo#stud", which it shouldn't do.

To match at the end of the string, use the String.endsWith method.
if (str.endWiths("hello123#stud")) {
//bla bla
}
You might want to improve your code. You're using EditText right?
EditText.getText() does not return null
You should create a local variable for repeated code access the text inside EditText: String emailStr = etEmail.getText().toString()
It will increase readability a lot.

Related

How can I check if String contains the domain name listed in ArrayList having multiple domains in Java?

I'm trying to allow request from specific domains only which are listed in ArrayList, so I need to put a conditional check if URL contains the domains listed in ArrayList then allow otherwise throw an Exception.
Suppose my ArrayList = [abc.com, def.com, xyz.com]
I want to check if my URL contains any of these domains from ArrayList then return true else return false.
I tried below code, but it checks the domain name one by one.
However, it returns false if domain name is valid -
ArrayList = [abc.com, def.com, xyz.com]
public static boolean isListContainValidDomain(List<String> arraylist) {
String reqURL = "dev.def.com";
boolean isValid = true;
for (String str : arraylist) {
if(!reqURL.contains(str.toLowerCase())){
isValid = false;
}
}
return isValid;
}
Can anyone please help on this.
You should invert the condition. As it is now your function will only return true if your string contains all strings in the list.
public static boolean isListContainValidDomain(List<String> arraylist) {
String reqURL = "dev.def.com";
for (String str : arraylist) {
if (reqURL.contains(str.toLowerCase())) {
return true;
}
}
return false;
}
Why don't you construct a regex that incorporates all the domains. Basically your ArrayList = [abc.com, def.com, xyz.com] should be converted to a string that looks like (abc.com | def.com | xyz.com) then you can just do a single regex match.
You may be able to use Streams api:
public static boolean isListContainValidDomain(List<String> arraylist) {
final String reqURL = "dev.def.com";
boolean isValid = arraylist.stream().anyMatch(domain -> reqURL.contains(domain));
return isValid;
}
Since it would be possible for an url to have a domain name anywhere (abc.computer.xxx.com) I think you should use endsWith. Here is a solution using streams
boolean isOk = arrayList.stream().anyMatch( dom -> reqUrl.endsWith(dom.toLowerCase()));

Converting A String to a Boolean -- Java

I've been searching around stackoverflow, and I've found a few other questions on converting a string to a boolean, but I can't make it work. Perhaps it is just the way I am trying to use it is incorrect.
Anyways, I am trying to convert two different input strings "M" or "I" in to boolean for use in an if statement. What is basically want the functionality to be is this:
// the text that is retrieved is assumed to be either"M" or "I"
M=Input.getText
I=Input.getText
If M shows the value "M",
do stuff here
else if I shows the value "I",
do stuff here
else if neither above are true,
throw an exception here
I've tried any number of "toBoolean"s and "Boolean.valueof"s, but none of what I try is working.
PS, Sorry for not having actual code to work with, this is my first step, and thus I haven't built anything up around this piece.
You can use String's methods to check for whether it contains a given literal value, equals it, or equals ignoring case.
A draft condition would be:
if ("myValue".equalsIgnoreCase(myText)) {
// TODO
}
else if ("myOtherValue".equalsIgnoreCase(myOtherText)) {
// TODO
}
else {
// TODO
}
Here is the documentation in java.lang.String:
equals
equalsIgnorecase
contains
You also want to check the many other methods, such as startsWith, endswith, etc. etc.
Use this for one boolean:
boolean b = (M.equals("M") || I.equals("I"));
Or this for two boolean:
boolean booleanM = (M.equals("M"));
boolean booleanI = (I.equals("I"));
if(booleanM){
//do stuff here
}else if(booleanI){
//do stuff here
}else{
//do stuff here where both are false
}
This is the faster way if you need to verify more than one time, only one time use this:
if(M.equals("M")){
//do stuff here
}else if(I.equals("I")){
//do stuff here
}else{
//do stuff here where both are false
}
You can simply use boolean b = Input.getText().equalsIgnoreCase("YourTrueString"). This method will detect if the input text is exactly the same as "YourTrueString". If not, it'll return false. This way anything that isn't true becomes false.
From your pseudo code
// the text that is retrieved is assumed to be either"M" or "I"
M=Input.getText
I=Input.getText
If M shows the value "M",
do stuff here
else if I shows the value "I",
do stuff here
else if neither above are true,
throw an exception here
To Java
// In its own method for reuse, in case you want to extend character support
public boolean match(String character, String match) {
return character.equals(match);
}
You can then invoke this simple method
String m = Input.getText();
String i = Input.getText();
if (match(m, "M")) {
do stuff here
} else if (match(i, "I")) {
do stuff here
} else {
throw an exception here
}

Validating user input in JTextFields (Java)

I am trying to validate user input into text boxes. I am checking whether the text box is populated or not and if it's not I need to alert the user to which text box isn't populated. My problem is that I need a way of returning which text box / variable is empty. I am aware I will need to pass 2 values in, one being the content of the text box and the other, an identifier of the text box.
Currently I have this (found on StackOverflow) which checks if each variable in the array is populated.
public boolean areAllNotEmpty(String... text){
for(String s : text) {
if(s == null || "".equals(s)) {
return false;
}
}
return true;
}
I would like it to also return something like this (commented):
public boolean areAllNotEmpty(String... text){
for(String s : text) {
if(s == null || "".equals(s)) {
// return textbox name / value OR show alert box with "Forename missing" etc
return false;
}
}
return true;
}
I implemented this method before on a C# project but it requires passing in one text box at a time with multiple method calls which I'm guessing isn't great.
public static bool IsFieldNull(TextBox currentText, string type)
{
bool allOk = false;
if (currentText.Text == "")
{
MessageBox.Show("Error - '" + type + "' field cannot be left blank, please enter some data in this field");
currentText.Focus();
return allOk;
}
else
{
allOk = true;
return allOk;
}
This is how it is called in C#.
Validation.IsFieldNull(txtBoxFixtureDate, "Fixture Date") && Validation.IsFieldNull(txtBoxTime, "Time")
If any of that doesn't make sense, let me know.
Thanks for any help.
You could pass the components to the method and return ones that are empty like this:
public List<JTextField> getEmptyFields(JTextField... textFields) {
List<JTextField> emptyFields = new ArrayList<JTextField>();
for (JTextField field : textFields) {
if (field.getText().isEmpty()) {
emptyFields.add(field);
}
}
return emptyFields;
}
Then you can just check the size() of the returned list to determine if there was an empty field and deal with them accordingly.
It's not pretty useful to validate when a submit button is pressed, it's better to validate when the error is happening. You may consider using InputVerifier . Then you know when it's in valid state or not. Apart from that if you are using java7 or above you could take a look to JLayer to decorate components which are not in valid state. See here for more examples Decorate components with JLayer.

Altering return value of method

Lets say that I have a method that returns a String. I want to check if the returned String is equal to another String and if they are the same to set the returned String to be just "". How would I go about doing this.
Assuming the "original" string is str and the "other" string is anotherStr:
return str.equals(anotherStr) ? "" : str;
Notice that anyway you have to return something if the strings are different, I'm returning str, but you'll know what's the appropriate value to return in this case.
Use String.equals() to compare two strings in Java.
return str.equals("bla") ? "" : str;
Set up your check() method like this, where you pass in the String you want to check for, and run it at the end of the method...
public String check(String comparison){
// do some normal processing here, which ends up with a String 'result' that you want to return
...
// Do the check at the end
if (result.equals(comparison)){
return "";
}
else {
return result;
}
}
Alternatively, you can add the check into the method call itself, which doesn't require you to change the signature of the method...
String result = runMethod();
if (result.equals(comparison)){
result = "";
}

Java - Compare two strings and assign value to third variable?

this is my first so I'll try to add as much info as possible so I don't get yelled at. :-)
What I am trying to do is I have 2 variables that grab text from 2 fields and take only the first character from each and assign it to those values.
This is the code that I use to get the strings. They are 2 separate calls as you would.
try { var_ContactSurname = var_ContactSurname.substring(0,1);
}
catch (Exception e){
}
I have the above again with a different variable. Now to this point it does what I want. It grabs the first letter from the fields and assigns it to the variables.
So at this point I have two variables (say with an example charater of D and R).
var_ContactSurname = R
var_ContactLicenceNumber = D
What I want to do is compare those two variables and if they match I want to return a value of TRUE, else FALSE if they don't match.
That value has to be a string as well and be assigned to a new variable called var_ContactValidate.
if (var_ContactLicenceNumber.toLowerCase().equals()var_ContactSurname.toLowerCase()){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
No you may notice that there might be some code missing. I am using a rules engine that does a lot of the functions for me. I can use raw Java code to do other things (like this compare)...but that's the compare that I am having a problem with.
Any ideas for that compare would be greatly appreciated.
Thanks.
i would use the String method equalsIgnoreCase()
to assign a value to a field, use a single =, not double (==).
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname){
var_ContactValidate = "TRUE";
}
else {
var_ContactValidate = "FALSE";
}
check it
In addition to what already said - a simpler & more elegant version (without the if condition) could be:
var_ContactValidate = Boolean.toString(
var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname))
.toUpperCase();
Change your whole piece of code to:
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname)){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
This combines the case insensitivity that you want, and passes through the second string as an argument of the .equalsIgnoreCase function.
Also, I am not sure what you are trying to do with the line:
var_ContactValidate == "TRUE";
If you want to assign var_ContactValidate to "TRUE" then use a single equals sign '=' as a double equals '==' compares the values instead. You may also considering using a boolean rather than a string in this case.
Here is an implementation that also checks for null values and empty Strings:
public class SurnameAndLicenseValidator {
public static void main(String[] args) {
// FALSE
validateSurnameAndLicense(null, "jb78hq");
validateSurnameAndLicense("Johnson", null);
validateSurnameAndLicense(null, null);
validateSurnameAndLicense("", "jb78hq");
validateSurnameAndLicense("Johnson", "");
validateSurnameAndLicense("", "");
validateSurnameAndLicense("johnson", "xb78hq");
// TRUE
validateSurnameAndLicense("Johnson", "jb78hq");
validateSurnameAndLicense("johnson", "jb78hq");
}
private static String validateSurnameAndLicense(String surname,
String license) {
String result;
if (surname != null
&& surname.length() > 0
&& license != null
&& license.length() > 0
&& Character.toUpperCase(surname.charAt(0)) == Character
.toUpperCase(license.charAt(0))) {
result = "TRUE";
} else {
result = "FALSE";
}
System.out.println(surname + " " + license + " " + result);
return result;
}
}
The main method is used as a unit test here. You might want to extract a real JUnit test from it, if you are into that kind of thing.

Categories