Checking JSP Input for "Empty" - java

In my testing, the following seems to cover everything I can think of in terms of ensuring that a field is populated. Can anyone think of a case I might have missed?
public static boolean isEmpty(final String string) {
return string != null && !string.isEmpty() && !string.trim().isEmpty();
}

The name is a bit misleading as the method is labeled "isEmpty" but will return true when it's not empty... but that's up to you.
I would change your AND statements to ORs and remove the middle term as it is superfluous e.g.
public static boolean isEmpty(final String string) {
return string == null || string.trim().isEmpty();
}
EXAMPLE:
if(isEmpty(null)){
System.out.println("Empty");
}else{
System.out.println("Not Empty");
}
if(isEmpty("")){
System.out.println("Empty");
}else{
System.out.println("Not Empty");
}
if(isEmpty(" ")){
System.out.println("Empty");
}else{
System.out.println("Not Empty");
}
if(isEmpty("Test")){
System.out.println("Empty");
}else{
System.out.println("Not Empty");
}
OUTPUT:
Empty
Empty
Empty
Not Empty

Why don't you just use a library?
One example is Apache's Common Utils:
StringUtils.isBlank()
StringUtils.isNotBlank()

Apache Commons StringUtils uses the following techniques:
isEmpty:
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
isBlank:
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}

You can just do:
public static boolean isEmpty(String string) { //don't make it final going in or you cant trim it.
string = string.trim();
return string != null || string.length() == 0;
}

Related

To check if string is palindrome using recursion?

There is something wrong with my code as one the testcase in my assignment is coming out wrong, giving me runtime error when I submit the code online. That testcase could be any String. I believe that everything is fine with the code as I have checked it manually for many testcases.
HERE IS THE CODE
public static boolean isStringPalindrome(String input) {
if(input.length()==0 || input.length()==1)
return true;
int first = 0;
int last = input.length()-1;
if(input.charAt(first) != input.charAt(last))
return false;
String str="";
for(int i=first+1;i<last;i++){
str = str+input.charAt(i);
}
boolean sa = isStringPalindrome(str);
return sa;
}
Sample Input
racecar
Output
true
Sample Input
pablo
Output
false
Your code appears to be overly complicated for recursively testing if the String is a palindrome. Something like,
public static boolean isStringPalindrome(String input) {
if (input == null) {
return false;
} else if (input.isEmpty() || input.length() == 1) {
return true;
}
int len = input.length() - 1;
return input.charAt(0) == input.charAt(len) //
&& isStringPalindrome(input.substring(1, len));
}
Is recursive without embedding a for loop. Because if you can do that, you should do something like
public static boolean isStringPalindrome(String input) {
if (input == null) {
return false;
} else if (input.isEmpty() || input.length() == 1) {
return true;
}
int len = input.length();
for (int i = 0; i <= len / 2; i++) {
if (input.charAt(i) != input.charAt(len - 1 - i)) {
return false;
}
}
return true;
}
A simpler way to check for palindrome can be:
public static boolean isPalindrome(String s)
{ if (input == null)
return false;
else if(s.length() == 0 || s.length() == 1)
return true;
/* check for first and last char of String:
* if they are same then do the same thing for a substring
* with first and last char removed. and carry on this
* until you string completes or condition fails.
*/
if(s.charAt(0) == s.charAt(s.length()-1))
return isPalindrome(s.substring(1, s.length()-1));
return false;
}
Update
You are getting runtime error(NZEC) which means non-zero exit code. It means your program is ending unexpectedly. I don't see any reason except that your program doesn't have a null check. Otherwise, I have gone through your code carefully, you are doing the same thing which I have suggested.

Java check if parameter contains vowels

I am kind of new to Java coming from a JavaScript background. I am trying to check if a given parameter contains vowels and if so, return true. This is what I have so far:
public class StringUtils {
public static boolean isVowel(String s) {
String x = s.toLowerCase();
if(x.indexOf('a' || 'e' || 'i' || 'o' || 'u')) {
return true;
} else {
return false;
}
}
}
How should this be done in Java?
You can try this method to check for vowels:
public static boolean isVowel(char c) {
return "AEIOUaeiou".indexOf(c) != -1;
}
You can try regex also:
yourString.matches("[AEIOUaeiou]")
smth like that

Can't figure out how to fix my code

Hi for the past few hours i have been trying to fix my code. The problem is that when I go to check if "" is an integer is returns true when it should be false. I know why this is happening, it is because it doesn't enter the for loop and returns true , but I can't seem to figure out how to make it return false for "". I can provide more info if needed.
public boolean isInteger(String str)
{
for (int x = 0, n = str.length(); x < n; x++)
{
char c = str.charAt(x);
if (c < '0' || c > '9')
{
if (c != 0 || c != '-')
{
return false;
}
}
}
return true;
}
Thank you for spending your time on trying to help me :)
You could check valid input (ie, a string with length = 0) and return false before you ever try the loop. You're correct, though, it's not entering the loop and just returning true.
--edit--
Something like
if (string == null) || (string.length() == 0){
return false
}
In your algorithm, an empty string will always return true. You just need to add a check:
if(str==null || str.length()==0) return false;
Alternatively, you can use this function:
public static boolean isInteger(String str)
{
try
{
Integer.parseInt(str);
return true;
}
catch(NumberFormatException e)
{
return false;
}
}

How can I use instanceof Keyword Java

Is this the right way of validating using the instanceof keyword in java? Can I not use the || operator with this keyword? I am seeing errors in the line where I am writing the if condition to check if FieldName < = 0 and also when I am checking if it is equal to null or empty. Can anyone help me with the right way of writing the following piece of code. Thank you.
public static boolean validation(Object FieldName, String Name) {
if(FieldName instanceof Integer) {
if ((int) FieldName < = 0) {
errorCode = "EXCEPTION";
errorMsg = "Required field " + Name + " was not provided";
logger.debug(Name+ " is null ");
return true;
}
else {
}
}
else if (FieldName instanceof String) {
if(FieldName == null || FieldName.equals("")) {
errorCode = "EXCEPTION";
errorMsg = "Required field " +Name+" was not provided";
logger.debug(Name+" is null ");
return true;
}
//Here I check the fields for null or empty
}
Why not have two methods, one which takes an Integer and validates that, and one that validates Strings? Would that be simpler?
The line needs to be changed to
if (((int) FieldName) <= 0) {
when you don't put the parentheses around the cast completely the compiler will still believe it is an object and not an integer.
Try this. change the if and else body according to you
public static boolean validation(Object FieldName, String Name) {
if (FieldName instanceof Integer) {
if (((Integer)FieldName) <= 0) {
//an integer <= 0
return true;
} else {
// an integer >= 0
return true;
}
} else if (FieldName instanceof String) {
if (FieldName == null || FieldName.equals("")) {
// a String empty or null
return true;
}
else {
// a String non empty
return true;
}
}
return false;
}

Method always returns true?

I have a method that is being called to validate that an IP address is assignable. No matter what I pass to it, it is always returning true. What do I need to set the return as to get this method working properly?
public boolean checkValidIPClass(String x) {
for (int i = 0; i < 4; i++) {
try {
if (retString.equals("A")) {
if ((intParts[1] == 0) && (intParts[2] == 0) && (intParts[3] == 0))
return false;
if ((intParts[1] == 255) && (intParts[2] == 255) && (intParts[3] == 255))
return false;
}
if (retString.equals("B")) {
if ((intParts[2] == 0) && (intParts[3] == 0))
return false;
if ((intParts[2] == 255) && (intParts[3] == 255))
return false;
}
if (retString.equals("C")) {
if (intParts[3] == 0)
return false;
if (intParts[3] == 255)
return false;
}
} //ends try
catch (NumberFormatException nfe) {
return false;
} //ends catch
} //ends for
return true;
}
retString is making it to the method and is a string that was returned from another method that checks what class the IP address is and assigns it, this was verified with a print statement. Thanks!
EDIT: How has this been answered and downvoted? My question wasn't about comparing the strings, it was about the method always returning true even when I know the if statements should be catching the error and returning false?
EDIT2: Updated my code.
I don't get why you're doing a loop, but you could try this:
public boolean checkValidIPClass(String ipClass, String ipAddress)
{
if (ipClass.contentEquals("A"))
{
if (ipAddress.endsWith("0.0.0") || ipAddress.endsWith("255.255.255"))
return false;
}
else if (ipClass.contentEquals("B"))
{
if (ipAddress.endsWith("0.0") || ipAddress.endsWith("255.255"))
return false;
}
else if (ipClass.contentEquals("C"))
{
if (ipAddress.endsWith("0") || ipAddress.endsWith("255"))
return false;
}
return true;
}
Since you're just checking the ending array parts of the IP address, you don't need to break it into an array, just leave it as a string.
And keep in mind that this would only satisfy IPv4 formatted IP addresses. It will not work for IPv6 formatted addresses

Categories

Resources