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.
Related
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.
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/
I'm reading in a text file formated like
word
definiton
word
definition
definition
word
definition
So I need to keep try of whether I'm in a definition or not based on when I reach those emtpy lines. Thing is, BufferedReader discards \n characters, and somehow comparing that empty line to String "" is not registering like I thought it would. How can I go about doing this.
Make sure you use: "".equals(myString) (which is null-safe) not myString == "".
After 1.6, you can use myString.isEmpty() (not null-safe)
You can use myString.trim() to get rid of extra whitespace before the above check
Here's some code:
public void readFile(BufferedReader br) {
boolean inDefinition = false;
while(br.ready()) {
String next = br.readLine().trim();
if(next.isEmpty()) {
inDefinition = false;
continue;
}
if(!inDefinition) {
handleWord(next);
inDefinition = true;
} else {
handleDefinition(next);
}
}
}
The BufferedReader.readLine() returns an empty string if the line is empty.
The javadoc says:
Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached.
If you don't appear to be seeing an empty String, either the line is not empty, or you are not testing for an empty String correctly.
line = reader.readLine();
if ("".equals(line)) {
//this is and empty line...
}
I do not know how did you try to check that string is empty, so I cannot explain why it did not work for you. Did you probably use == for comparison? In this case it did not work because == compares references, not the object content.
This code snippets skips the empty line and only prints the ones with content.
String line = null;
while ((line = br.readLine()) != null) {
if (line.trim().equals("")) {
// empty line
} else {
System.out.println(line);
}
}
Lines only containing whitespace characters are also skipped.
try (BufferedReader originReader = getReader("now")) {
if (StringUtils.isEmpty(originReader.readLine())) {
System.out.printline("Buffer is empty");
}
Given a File and a Scanner object,
File simpleFile = ranFi.getSelectedFile();
Scanner text = new Scanner(simpleFile);
and these two commonplace statements:
while(text.hasNext())
{
String currentLine = text.nextLine();
I'm trying to use Scanner/String class logical statements in a single if-statement clause which reads first line of file under a given matching regular expressions, such as:
String fp100 = "[S][:][A-Ze0-1]";
String fp200 = "[S][:][A-Z0-1][A-Z0-1]";
//other regexes…
and then invoke the appropriate Scanner/String class methods in same if-statement clause to read to second and onward/acceptable lines. I've read javadoc up and down but haven't figured out yet. Using currentLine.matches(regex) and text.nextLine().matches(regex), this code compiled,
if(currentLine.matches(fp100)||currentLine.matches(fp200)||
currentLine.matches(fp300) && text.nextLine().matches(fp100)||
text.nextLine().matches(fp101) || text.nextLine().matches(fp200)||
text.nextLine().matches(fp201) || text.nextLine().matches(fp300)||
text.nextLine().matches(fp301))
{
but throws an No Such Element Exception immediately. What am I doing wrong?
Thank you in advance for your time. EDIT: I've included the stack trace, but removed the source code since this is project related.
I see two problems:
When you perform the if condition, text.nextLine() may not be available.
if you mean to say, execute the if when any of the currentLine Matches + any of the nextLine match as true then wrap || arguments in a brace as:
if((currentLine.matches(fp100)||currentLine.matches(fp200)||
currentLine.matches(fp300)) &&
(text.nextLine().matches(fp100)||
text.nextLine().matches(fp101) || text.nextLine().matches(fp200)||
text.nextLine().matches(fp201) || text.nextLine().matches(fp300)||
text.nextLine().matches(fp301)))
I think you wanted to write your while loop something like this:
while(text.hasNextLine()){
String currentLine = text.nextLine();
String nextLine = "";
if(text.hasNextLine())[
nextLine = text.nextLine();
}
/**ACC conditions*/
if((currentLine.matches(fp100)||currentLine.matches(fp200)
|| currentLine.matches(fp300))
&& (nextLine.matches(fp100)|| nextLine.matches(fp101)
|| nextLine.matches(fp200)
|| nextLine.matches(fp201) || nextLine.matches(fp300)
|| nextLine.matches(fp301)) {
//current line is OK
System.out.println(currentLine);
output.write(currentLine);
output.write("\n");
abc1List.add(currentLine);
lineOK++;
//next line is OK
System.out.println(nextLine);
output.write(nextLine);
output.write("\n");
abc1List.add(nextLine);
// <-- not sure if you want OK as 1 or 2 here
lineOK++;
} /**REJ conditions*/
else if(!currentLine.matches(fp100)||!currentLine.matches(fp101)||
!currentLine.matches(fp200)||!currentLine.matches(fp201)||
!currentLine.matches(fp300)||!currentLine.matches(fp301)){
System.out.println("invalid cfg; terminating....");
System.exit(0);
}
}//end of while
Your while loop should start with while(text.hasNextLine()) if you are using text.nextLine().matches(regex) inside the loop. Be careful. If text.hasNext() evaluates to true, it doesn't mean that text.nextLine() will be non-null.
private int Index(String[] match,String keyword){
int m=0;
keyword=keyword+"1";
match[m]=match[m]+"1";
System.out.println("match:"+match[m]);
System.out.println("keyword:"+keyword);
System.out.println(match[m].equals(keyword));
while(!(match[m].equals("")) && !(match[m].equals(null))){
System.out.println("yes");
if(match[m].equals(keyword)){
break;
}
else
m++;
}
return m;
}
And I am getting following output (value of keyword is sparktg):
match:sparktg
1
keyword:sparktg1
false
Why in the case of match[m], there is a new line between "sparktg" & "1"?
If you have no control over the input, you can do a trim() before you use the inputs. This eliminates any \n and spaces.
if(match[m] != null) {
System.out.println("match:"+match[m].trim());
}
if(keyword != null) {
System.out.println("keyword:"+keyword.trim());
}
You can make it cleaner by writing a utility method to do this.
public String sanitize(String input) {
return input != null ? input.trim() : null;
}
and use it as so:
match[m] = sanitize(match[m]);
keyword = sanitize(keyword);
The only reason I can see is that match[0] already ends in a newline. You should check by outputting match[0] before adding the "1". A good practice is to output in this form:
System.out.println("|"+match[0]+"|");
...thus using the | to clearly mark where your string starts and ends.
You can use trim() to cut off any whitespace, including newlines:
match[m] = match[m].trim() + "1";
However, this will also remove spaces and tabs, which may or may not be a problem for you. When I compare strings, I often trim both strings first, just to be safe, but only if you are disregarding whitespace.
Try this. Replace all the new line before parsing.
private static int Index(String[] match,String keyword){
int m=0;
for(int k=0;k<match.length;k++){
if(match[k]!=null)
match[k]= match[k].replace("\n", "");
}
if(keyword!=null)
keyword= keyword.replace("\n", "");
keyword=keyword+"1";
match[m]=match[m]+"1";
System.out.println("match:"+match[m]);
System.out.println("keyword:"+keyword);
System.out.println(match[m].equals(keyword));
while(!(match[m].equals("")) && !(match[m].equals(null))){
System.out.println("yes");
if(match[m].equals(keyword)){
break;
}
else
m++;
}
return m;
}
That is not the answer, but notation about the code
match[m].equals(null) will throw an NullPointerException. The right way to check if match[m] not equals null is: mathc[m] != null before calling any method of your object. So use this:
match[m] != null && !match[m].equals("")
instead of this:
!match[m].equals("") && !match[m].equals(null)