I'm trying to accept a user field in the form of a jTextArea (Search box). Then take this text and compare it against an ID OR Name and return if its inside of any.
Compare User Entry to ID
Compare User Entry to Name
Essentially check the user entry against a String and an Int.
I've got the following however am getting NumberFormatException.
String name = "Window";
int id = 12;
if (name.contains(searchText.getText().toLowerCase()) || id == Integer.valueOf(searchText.getText().replaceAll("[^0-9]", ""))) {
// TRUE STATEMENT
}
So if a user enters "Win" it will return true. If they enter "test" it will return false. However if they enter "1","2" or "12" it will return true since the ID contains these.
I think I'm overthinking this one and could use some help.
Thanks in advance
if (name.toLowerCase().contains(searchText.getText())
|| Integer.toString(id).contains(searchText.getText())) {
System.out.println("TRUE");
}
Related
so in my program the user has to register and one of the fields to enter is the phone number.
I want to check if the first 3 numbers they enter is valid or not
if (TextUtils.isEmpty(PhoneNumber) || PhoneNumber != "055, 050, 056, 052") {
PhoneNumber.setError("Please enter a valid phone number")
return;`
}
this is my code but it set off so many errors, can somebody please help me with this?
PhoneNumber != "055, 050, 056, 052" is wrong.
You can create a string array and store them there.
String okNums = {"055", "050", "056", "052"};
and then check if the phone number is valid
if (TextUtils.isEmpty(PhoneNumber) ||
!Arrays.asList(okNums ).contains(PhoneNumber)) {
PhoneNumber.setError("Please enter a valid phone number")
return;`
}
turn your pattern into an array and search if the phone is beginning with any of those
String d = "055, 050, 056, 052";
String p = "055 66";
String[] pArr = d.split(",");
for (String patt : pArr ) {
System.out.println(patt.trim());
System.out.println(p.indexOf(patt)==0);
}
//Get the string from the edit text by:
String number = yourEditText.getText().toString();
if(number != null && number.matches("639[0-9]{9}"))
//do what you need to do for valid input
else
//do what you need to do for invalid input
matches() ensures that the entire string cooresponds (exactly) to the regular expression that it takes. 639[0-9]{9} says that the string must start off with 639 and then be followed by exactly 9 digits (0-9). If you wanted to match "639" followed by 7 to 9 numbers, for example, you would use: 639[0-9]{7,9}. Regular expressions:
A simple solution would be .startsWith()
if (!PhoneNumber.startsWith("055") || !PhoneNumber.startsWith("050") || !PhoneNumber.startsWith("056") || !PhoneNumber.startsWith("052")) {
// does not match
}
Another option is to use a regex for this
if (!PhoneNumber.matches("^(055|050|056|052)\d+$")){
// does not match
}
The worst thing you had done is, your comparison. You can't compare like this, when you need to compare with several values. Instead you have to use something like List#contains method to check whether your PhoneNumber or not.
String[] check = {"055", "050", "056", "052" };
if (TextUtils.isEmpty(PhoneNumber) || Arrays.asList(check).contains(PhoneNumber.getText().toString())) {
PhoneNumber.setError("Please enter a valid phone number")
return;
}
Alright so from what I understood here is a solution, if the phone number has is a one full string you can extract the first 3 numbers using this:
String s="052487978";
String ex = s.substring(0,3));//052
Create a int array and store all the valid options in there
int[] array = {055, 050, 056, 052}; and covert the string ex to int int value = Integer.parseInt(ex); and check if its available in the string that contains valid options.
boolean contains = IntStream.of(array ).anyMatch(x -> x == value);
If it is true its valid and if its false its invalid.
I am in the process of creating a java Web Application, to do enable users to create fair strong credentials I would like to prevent them from entering weak passwords. I'd like to follow the basic rules of it must contain at least eight characters and at least one number and one symbol. I would appreciate a point in the right direction, many thanks!
Two solutions :
1.) You can use regular expression for the password requirements and compare the password entered by the user with that expression, if the pattern of password matches the regular expression then you can let the user register otherwise you can show an error.
2.) When user enters a password, you can call a function which would check whether:
a. password contains at least one number.
b. password contains at least one special character.
c. is the length of password entered by user greater than the minimum length etc...
this function will return true or false depending on whether password is accepted or not.
Hope this helps you.
You can check user's entered password by this java-code,
public static boolean isValidPassword(String userEnteredPassword) {
boolean atleastOneUpper = false;
boolean atleastOneLower = false;
boolean atleastOneDigit = false;
if (userEnteredPassword.length() < 8) { // If its less then 8 characters, its automatically not valid
return false;
}
for (int i = 0; i < userEnteredPassword.length(); i++) { // Lets iterate over only once. Saving time
if (Character.isUpperCase(userEnteredPassword.charAt(i))) {
atleastOneUpper = true;
}
else if (Character.isLowerCase(userEnteredPassword.charAt(i))) {
atleastOneLower = true;
}
else if (Character.isDigit(userEnteredPassword.charAt(i))) {
atleastOneDigit = true;
}
}
return (atleastOneUpper && atleastOneLower && atleastOneDigit); // Return true IFF the userEnteredPassword is atleast eight characters long, has atleast one upper, lower and digit
}
I am developing a questions and answers game that asks questions to users and for answer instead of keyboard different letters are provided and the user has to select the correct letters to form a word i.e. the answer. The combination of letters should match the correct answer...if it does not an error should appear.
Store the selected letters into a string and use equals to check if it matches the correct answer.
String selectedLetters = "abc";
String answer = "abc";
if(selectedLetters.equals(answer)) {
// Correct answer
} else {
// Incorrect answer
}
You can create the String using:
String selectedLetters = "";
selectedLetters.append('a'); // This adds the letter "a" to the string
And check if the given answer is correct when the strings are the same length.
if (selectedLetters.length() == answer.length) {
if(selectedLetters.equals(answer)) {
// Correct answer
} else {
// Incorrect answer
}
}
am implementing a String matching algorithm for a username database. My method takes an existing Username database and a new username that the person wants and it checks to see if the username is taken. if it is taken the method is supposed to return the username with a number that isn't taken in the database.
Example:
"Justin","Justin1", "Justin2", "Justin3"
Enter "Justin"
return: "Justin4" since Justin and Justin with the numbers 1 thru 3 are already taken.
In my code sample below, newMember returns null and I don't know why. It should return "justin4"
public class UserName {
static String newMember(String[] existingNames, String newName){
boolean found = false;
boolean match = false;
String otherName = null;
for(int i = 0; i < existingNames.length;i++){
if(existingNames[i].equals(newName)){
found = true;
break;
}
}
if(found){
for(int x = 1; x < 100 ; x++){
for(int i = 0; i < existingNames.length;i++){
if(existingNames[i].equals(newName + x))
match = true;
}
if(!match)
otherName = newName + x;
}
// It returns NULL instead of "Justin4". Its as if otherName doesn't
// change after its initialization.
return otherName;
} else return newName;
}
public static void main(String[] args){
String[] userNames = new String[4];
userNames[0] = "Justin1";
userNames[1] = "Justin2";
userNames[2] = "Justin3";
userNames[3] = "Justin";
System.out.println( newMember(userNames, "Justin"));
}
}
You need to reset match to false at the start of each x loop iteration. Otherwise, it will match an earlier number, and match will be stuck at true for the rest of the x iterations. You'll never see that it doesn't match for a larger x.
You should also break out of the x loop when you find a name, otherwise you will keep overwriting otherName with a larger x.
You may wish to break out of the i loop (although you don't need to) for efficiency; no sense checking the rest if you already know there's a match.
You're never resetting your match variable. So if it is set to true in the first run, it is never set to false again, and if(!match) otherName = newName + x; never happens. Change this
if(existingNames[i].equals(newName + x))
match = true;
to
match = existingNames[i].equals(newName + x);
I don't know if case sensitivity is also important for you, in which case you should be careful to use equalsIgnoreCase method instead of equals in your case, just for safety. Also if your username database is a SQL database, I suggest doing this check against the database itself with a query, it should be somewhat more efficient.
Otherwise yes, reset your match variable.
You also need to break of the outer for loop in the if(found), once you have the newName, along with resetting the boolean to false.
Or it will just get concatenated to a very long userName.
I wrote like this; but it fails to integer only textfields
if(textField_1.getText().length()==0)
JOptionPane.showMessageDialog(null, "enter text in textfield");
Please help...
Typically, when you are validating user input in Java, you will want to check for both null and empty string values. To check String objects for equality, you must use the .equals() method (not the == operator). Thus, a check for an empty String value might look something like this:
if ( val == null || val.trim().equals( "" ) )
{
// handle empty String case
}
else
{
// handle non-empty String case
}
Hope this helps
if(textField_1.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "enter text in textfield");
}