Empty string is...never empty - java

No matter what string test I use, I can never get my empty string to evaluate as true. In all cases, debugger says: string: "", but it won't enter the if loop. I've tried:
if (boolean isEmpty = TextUtils.isEmpty(kfl)) {
if (string.isEmpty()) {
if (string == "") {
if (string.length() == 0) {
if (string.equals("")) {
if (string.equals(null)) {
if (string.equals("null")) {
What else could "" possibly mean?

It contains the byte order mark:
0xEF,0xBB,0xBF
You could try explicitly looking for the hex sequence.

Related

Check if any part of a string input is not a number

I couldnt find an answer for this in Java, so I'll ask here. I need to check if 3 parts of a string input contains a number (int).
The input will be HOURS:MINUTES:SECONDS (E.g. 10:40:50, which will be 10 hours, 40 minutes and 50 seconds). So far I am getting the values in String[] into an array by splitting it on :. I have parsed the strings into ints and I am using an if statement to check if all 3 parts is equal or larger than 0. The problem is that if I now use letters I will only just get an error, but I want to check if any of the 3 parts contains a character that is not 0-9, but dont know how.
First I thought something like this could work, but really dont.
String[] inputString = input.split(":");
if(inputString.length == 3) {
String[] alphabet = {"a","b","c"};
if(ArrayUtils.contains(alphabet,input)){
gives error message
}
int hoursInt = Integer.parseInt(inputString[0]);
int minutesInt = Integer.parseInt(inputString[1]);
int secondsInt = Integer.parseInt(inputString[2]);
else if(hoursInt >= 0 || minutesInt >= 0 || secondsInt >= 0) {
successfull
}
else {
gives error message
}
else {
gives error message
}
In the end I just want to check if any of the three parts contains a character, and if it doesnt, run something.
If you are sure you always have to parse a String of the form/pattern HH:mm:ss
(describing a time of day),
you can try to parse it to a LocalTime, which will only work if the parts HH, mm and ss are actually valid integers and valid time values.
Do it like this and maybe catch an Exception for a wrong input String:
public static void main(String[] arguments) {
String input = "10:40:50";
String wrongInput = "ab:cd:ef";
LocalTime time = LocalTime.parse(input);
System.out.println(time.format(DateTimeFormatter.ISO_LOCAL_TIME));
try {
LocalTime t = LocalTime.parse(wrongInput);
} catch (DateTimeParseException dtpE) {
System.err.println("Input not parseable...");
dtpE.printStackTrace();
}
}
The output of this minimal example is
10:40:50
Input not parseable...
java.time.format.DateTimeParseException: Text 'ab:cd:ef' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalTime.parse(LocalTime.java:441)
at java.time.LocalTime.parse(LocalTime.java:426)
at de.os.prodefacto.StackoverflowDemo.main(StackoverflowDemo.java:120)
I would personally create my own helper methods for this, instead of using an external library such as Apache (unless you already plan on using the library elsewhere in the project).
Here is an example of what it could look like:
public static void main(String[] arguments) {
String time = "10:50:45";
String [] arr = time.split(":");
if (containsNumbers(arr)) {
System.out.println("Time contained a number!");
}
//You can put an else if you want something to happen when it is not a number
}
private static boolean containsNumbers(String[] arr) {
for (String s : arr) {
if (!isNumeric(s)) {
return false;
}
}
return true;
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(.\\d+)?");
}
containsNumbers will take a String array as an input and use an enhanced for loop to iterate through all the String values, using the other helper method isNumeric that checks if the String is a number or not using regex.
This code has the benefit of not being dependent on Exceptions to handle any of the logic.
You can also modify this code to use a String as a parameter instead of an array, and let it handle the split inside of the method instead of outside.
Note that typically there are better ways to work with date and time, but I thought I would answer your literal question.
Example Runs:
String time = "sd:fe:gbdf";
returns false
String time = "as:12:sda";
returns false
String time = "10:50:45";
returns true
You can check the stream of characters.
If the filter does not detect a non-digit, return "Numeric"
Otherwise, return "Not Numeric"
String str = "922029202s9202920290220";
String result = str.chars()
.filter(c -> !Character.isDigit(c))
.findFirst().isEmpty() ? "Numeric"
: "Not Numeric";
System.out.println(result);
If you want to check with nested loop you can see this proposal:
Scanner scanner = new Scanner(System.in);
String [] inputString = scanner.nextLine().split(":");
for (int i = 0; i < inputString.length; i++) {
String current = inputString[i];
for (int k = 0; k < current.length(); k++) {
if (!Character.isDigit(current.charAt(k))) {
System.out.println("Error");
break;
}
}
}
you could use String.matches method :
String notANum= "ok";
String aNum= "7";
if(notANum.matches("^[0-9]+$") sop("no way!");
if(aNum.matches("^[0-9]+$") sop("yes of course!");
The code above would print :
yes of course
The method accepts a regex, the one in the above exemple is for integers.
EDIT
I would use this instead :
if(input.matches("^\d+:\d+:\d+$")) success;
else error
You don't have to split the string.
I tried to make your code better, take a look. You can use Java regex to validate numbers. also defined range for time so no 24:61:61 values is allowed.
public class Regex {
static boolean range(int timeval,int min,int max)
{
boolean status=false;
if(timeval>=min && timeval<max)
{status=true;}
return status;
}
public static void main(String[] args) {
String regex = "[0-9]{1,2}";
String input ="23:59:59";
String msg="please enter valid time ";
String[] inputString = input.split(":");
if(inputString[0].matches(regex) && inputString[1].matches(regex) && inputString[2].matches(regex) )
{
if(Regex.range(Integer.parseInt(inputString[0]), 00, 24) &&Regex.range(Integer.parseInt(inputString[1]), 00, 60) && Regex.range(Integer.parseInt(inputString[2]), 00, 60))
{msg="converted time = " + Integer.parseInt(inputString[0]) + " : " +Integer.parseInt(inputString[1])+ " : " +Integer.parseInt(inputString[2]) ;}
}
System.out.println(msg);
}
}

Java - How to validate this string?

Do it exists a tool in Java to do this type of task below?
I got this hard typed String: {[1;3] || [7;9;10-13]}
The curly brackets {} means that is required
The square brackets [] means a group that is required
The double pipe || means a "OR"
Reading the string above, we get this:
It's required that SOME STRING have 1 AND 3 OR 7 AND 9 AND 10, 11, 12 AND 13
If true, it will pass. If false, will not pass.
I'm trying to do this in hard coding, but I'm felling that there is an easier or a RIGHT WAY to this type of validation.
Which type of content I must study to learn more about this?
I started with this code, but I'm felling that is not right:
//Gets the string
String requiredGroups = "{[1;3]||[7;9;10-13]}";
//Gets the groups that an Object belongs to
//It will return something like 5,7,9,10,11,12
List<Integer> groupsThatAnObjectIs = object.getListOfGroups();
//Validate if the Object is in the required groups
if ( DoTheObjectIsInRequiredGroups( groupsThatAnObjectIs, requiredGroups ) ) {
//Do something
}
I'm trying to use this iterator to get the required values from the requiredGroups variable
//Used for values like {[1;3]||[9;10;11-15]} and returns the required values
public static void IterateRequiredValues(String values, List<String> requiredItems) {
values = values.trim();
if( !values.equals("") && values.length() > 0 ) {
values = values.replace("{", "");
values = values.replace("}", "");
String arrayRequiredItems[];
if ( values.contains("||") ) {
arrayRequiredItems = values.split("||");
}
//NOTE: it's not done yet
}
}
So the rules are not really clear to me.
For example, are you only focussing on || or do you also have &&?
If I look at your example, I can derive from it that the && and operators are implicit in the ;.
None the less, I have made a code example (without much regex) that checks your rules.
First you need to begin with the || operator.
Put all the different OR statements into a String block.
Next you will need to check each element in the String block and check if the input value contains all block values.
If so then it must be true that your input string contains all the rules set by you.
If your rule consists of a range, you must first fully fill the range block
and then do the same with the range block as you would with the normal rule value.
Complete code example below.
package nl.stackoverflow.www.so;
import java.util.ArrayList;
import java.util.List;
public class App
{
private String rules = "{[1;3] || [7;9;10-13] || [34;32]}";
public static void main( String[] args )
{
new App();
}
public App() {
String[] values = {"11 12", "10 11 12 13", "1 2 3", "1 3", "32 23", "23 32 53 34"};
// Iterate over each value in String array
for (String value : values) {
if (isWithinRules(value)) {
System.out.println("Success: " + value);
}
}
}
private boolean isWithinRules(String inputValue) {
boolean result = false;
// || is a special char, so you need to escape it with \. and since \ is also a special char
// You need to escape the \ with another \ so \\| is valid for one | (pipe)
String[] orRules = rules.split("\\|\\|");
// Iterate over each or rules
for (String orRule : orRules) {
// Remove [] and {} from rules
orRule = orRule.replace("[", "");
orRule = orRule.replace("]", "");
orRule = orRule.replace("{", "");
orRule = orRule.replace("}", "");
orRule.trim();
// Split all and rules of or rule
String[] andRules = orRule.split(";");
boolean andRulesApply = true;
// Iterate over all and rules
for (String andRule : andRules) {
andRule = andRule.trim();
// check if andRule is range
if (andRule.contains("-")) {
String[] andRulesRange = andRule.split("-");
int beginRangeAndRule = Integer.parseInt(andRulesRange[0]);
int endRangeAndRule = Integer.parseInt(andRulesRange[1]);
List<String> andRangeRules = new ArrayList<String>();
// Add all values to another rule array
while (beginRangeAndRule < endRangeAndRule) {
andRangeRules.add(Integer.toString(beginRangeAndRule));
beginRangeAndRule++;
}
for (String andRangeRule : andRangeRules) {
// Check if andRule does not contain in String inputValue
if (!valueContainsRule(inputValue, andRangeRule)) {
andRulesApply = false;
break;
}
}
} else {
// Check if andRule does not contain in String inputValue
if (!valueContainsRule(inputValue, andRule)) {
andRulesApply = false;
break;
}
}
}
// If andRules apply, break and set bool to true because string contains all andRules
if (andRulesApply) {
result = true;
break;
}
}
return result;
}
private boolean valueContainsRule(String val, String rule) {
boolean result = true;
// Check if andRule does not contain in String inputValue
if (!val.contains(rule)) {
result = false;
}
return result;
}
}

How to keep a java variable a string when it begins with leading zeros

I have a string that contains value "001" that I need to evaluate as a string, however java keeps evaluating as an integer. Here is my simple sample code:
String equipmentCode = "001";
boolean questionable = StringUtils.equals(EquipmentCode,"???");
boolean emptyStuff = StringUtils.isNotEmpty(EquipmentCode);
if (questionable == false && emptyStuff == true) {
return true;
} else {
return false;
}
This fails on the StringUtils.equals line since it's evaluating EquipmentCode as an int. How can I ensure it's evaluated as a string? tia

Check whitespaces and isempty

I am looking for a if statement to check if the input String is empty or is only made up of whitespace and if not continue with the next input. Below is my code so far which gives an error when I input a whitespace.
name = name.trim().substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
if(name != null && !name.isEmpty() && name.contains(" ")) {
System.out.println("One");
} else {
System.out.println("Two");
}
The reason it gives you an error is that trim() removes all leading and trailing whitespace [edited], so then your string is empty. At that point, you call substring(0,1), so it will be out of range.
I would write this as the following.
name = name == null ? "" : name.trim();
if(name.isEmpty()) {
System.out.println("Null, empty, or white space only name received");
} else {
System.out.println("Name with at least length one received");
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
}
I think, if you want to use just String methods, then you'll need matches(regex), possibly more than one.
I haven't tested this, but it might work...
String emptyOrAllWhiteSpace = "^[ \t]*$";
if (name == null || name.matches(emptyOrAllWhiteSpace)) {
// first thing.
} else {
// second thing.
}
There are alternatives in the Apache Commons Lang library - StringUtils.isEmpty(CharSequence), StringUtils.isWhitespace(CharSequence).
Guava has another helper Strings.isNullOrEmpty() which you can use.

Finding if a specific character exists at a specific index

so I'm trying to figure out how to create a condition for my decision structure. I'm making a program that converts military time to conventional time. When times are entered, they must be in a XX:XX format, where X equals a digit. I'm wondering, how can I make a validation that checks to make sure that ":" always exists as a colon and is in the same spot?
myString.charAt(5) == ':'
Just change 5 to whatever you need, and check string length before you do this, so you don't ask for something past the end of a short string.
You could search the string with indexOf(), which returns the index at which the character is found. This will check if a colon is in the string and if it's in the right position.
if("10:00".indexOf(':') == 2)
// do something
It will return -1 if the value is not found. Check out the java documentation for more information.
Here is the answer for it
Suppose you had string that contains XX:XX
yourString="XX:XX"
yourString.contains(":") - return true - if exists
":" takes the 3rd position. So it will be 2(0,1,2)
yourString.charAt(2) == ':'
Together , it will be
if(yourString.contains(":") && yourString.charAt(2) == ':'){
//your logic here
}else{
something here
}
Here is one approach to that,
String[] test = new String[] { "00:00", "NN:NN", "12,13", "12:13" };
for (String fmt : test) {
boolean isValid = true;
for (int i = 0; i < fmt.length(); i++) {
char c = fmt.charAt(i);
if (i == 2) {
if (c != ':') { // here is the colon check.
isValid = false;
break;
}
} else {
// This checks for digits!
if (!Character.isDigit(c)) {
isValid = false;
break;
}
}
}
System.out.println(fmt + " is " + isValid);
}
Output is
00:00 is true
NN:NN is false
12,13 is false
12:13 is true
#WillBro posted a good answer but I give you another option:
myString.indexOf(":") == 5
With indexOf you can also look for full String inside a String.
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
But for string format validations I suggest you to use Regular Expresions.
Here's a full example that does what you want to do:
http://www.mkyong.com/regular-expressions/how-to-validate-time-in-24-hours-format-with-regular-expression/

Categories

Resources