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");
}
Related
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");
}
I want to be able to print a string that doesn't contain the words "Java", "Code" or "String", though I am unsure on how to achieve this as I thought this would be achieved by using '!' (NOT). However, this is not the case as the string is still printed despite the inclusion of the words I want to forbid.
Any advice on how to achieve this would be greatly appreciated, thanks in advance.
System.out.println("Type in an input, plez?");
String userInput6 = inputScanner.nextLine();
if (!userInput6.toLowerCase().contains("Java") || !userInput6.toLowerCase().contains("Code") || !userInput6.toLowerCase().contains("String")) {
System.out.println("I see your does not string contain 'Java', 'Code' or 'String, here is your string:- " + userInput6);
} else {
System.out.println("Your string contains 'Java, 'Code' or 'String'.");
}
I thought this would be achieved by using '!' (NOT)
It is. You just haven't applied it correctly to your situation:
You start with this statement:
userInput6.toLowerCase().contains("java") ||
userInput6.toLowerCase().contains("code") ||
userInput6.toLowerCase().contains("string")
which checks if the input contains any of these, and you wish to negate this statement.
You can either wrap the entire statement in parentheses (()) and negate that:
!(userInput6.toLowerCase().contains("java") ||
userInput6.toLowerCase().contains("code") ||
userInput6.toLowerCase().contains("string"))
or apply the DeMorgan's law for the negation of disjunctions which states that the negation of a || b is !a && !b.
So, as Carcigenicate stated in the comments, you would need
!userInput6.toLowerCase().contains("java") &&
!userInput6.toLowerCase().contains("code") &&
!userInput6.toLowerCase().contains("string")
instead.
Your statement is simply checking if the string doesn't contain at least one of these substrings. This means the check would only fail if the string contained all of these strings. With ||, if any operand is true, the entire statement is true.
Additionally, mkobit makes the point that your strings you are checking for should be entirely lowercase. Otherwise, you are checking if a .toLowerCased string contains an uppercase character - which is always false.
An easier way to think of it may be to invert your if statement:
if (userInput6.toLowerCase().contains("Java") ||
userInput6.toLowerCase().contains("Code") ||
userInput6.toLowerCase().contains("String")) {
System.out.println("Your string contains 'Java, 'Code' or 'String'.");
} else {
System.out.println("I see your does not string contain 'Java', 'Code' or 'String, here is your string:- " + userInput6);
}
Since you're using logical OR, as soon as one your contains checks it true, the entire condition is true. You want all the checks to be true, so you need to use logical AND (&&) instead
As #mk points out, you have another problem. Look at:
userInput6.toLowerCase().contains("Java")
You lower case the string, then check it against a string that contains an uppercase. You just removed all uppercase though, so that check will always fail.
Also, you can use regexp :)
boolean notContains(String in) {
return !Pattern.compile(".*((java)|(code)|(string)).*")
.matcher(in.toLowerCase())
.matches();
}
Or just inline it:
System.out.println("Type in an input, plez?");
String userInput6 = inputScanner.nextLine();
if (!Pattern.compile(".*((java)|(code)|(string)).*")
.matcher(userInput6.toLowerCase())
.matches()) {
System.out.println("I see your does not string contain 'Java', 'Code' or 'String, here is your string:- " + userInput6);
} else {
System.out.println("Your string contains 'Java, 'Code' or 'String'.");
}
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.
If i have written a number on a JLabel in java, how can I delete a specific digit from it? Is there any option by which I can get the current Cursor position or set it as required and then delete a particular digit of my choice? Kindly help...
You say you want to delete the last digit:
String txt = jLabel.getText();
jLabel.setText(txt.substring(0, txt.length()-1));
This should do the trick.
Edit:
You should also check for null or empty text:
String txt = jLabel.getText();
if(txt != null && !txt.isEmpty()) {
jLabel.setText(txt.substring(0, txt.length()-1));
}
Just delete the last char of the labels text, which is a String, if you are not sure if that String can be null in some cases, catch a NullpointerException.
But always ensure, that the text is not empty when you call substring to prevent a IndexOutOfBoundException:
String text = jLabelObject.getText();
try{
if(!text.isEmpty()){
jLabelObject.setText(text.substring(0, text.length()-1);
}
}catch(NullPointerException e){
jLabelObject.setText("");
}
Please take a look at the Java API Doc
substring(), isEmpty(), length()String
setText() JLabel
I want to add text to the EditText without losing the previous text.
Ex: when typing 74, i want to add the "4" to the text box without erasing the number "7" entered before.
public void add4()
{
res = (EditText)findViewById(R.id.editText1);
if(res.getText().toString() == "0")
{
res.setText("4");
}
else
{
// add number 4 to the remaining string
}
}
You can use the append method to append to existing text.
res.append("4");
http://developer.android.com/reference/android/widget/TextView.html#append(java.lang.CharSequence)
(As a side note, don't use == to compare strings, use .equals())
Try this:
I used the .equals method on a string object to avoid the NullPointerException that may happen if the object is null or not a string.
public void add4() {
res = (EditText)findViewById(R.id.editText1);
if( "0".equals(res.getText().toString()) )
{
res.setText("4");
}
else
{
res.append("4");
}
}
res.append("4"); or you can use res.setText(res.getText() + "4");