public final void nameErrorLoop () {
while (error) {
System.out.println("Enter the employee's name.");
setName(kb.next());
if (name.contains("[A-Za-z]")) {
error = false;
}
else {
System.out.println("The name can only contain letters.");
}
}
error = true;
}
Despite a similar setup working in a different method, this method becomes stuck in a constant loop because the if statement is always false. I've tried .matches(), and nothing that I found on the Interent has helped so far. Any ideas why? Thanks for your help in advance.
Edit: I just noticed as I was finishing the project, that trying to print 'name' later only shows the first name, and the last is never printed. Is there any way I can get the 'name' string to include both?
String.contains doesn't use regular expressions - it just checks whether one string contains another, in the way that "foobar" contains "oob".
It sounds like you want to check that name only contains letters, in which case you should be checking something like:
if (name.matches("^[A-Za-z]+$"))
The + (instead of *) will check that it's non-empty; the ^ and $ will check that there's nothing other than the letters.
If you expect it to be a full name, however, you may well want to allow spaces, hyphens and apostrophes:
if (name.matches("^[-' A-Za-z]+$"))
Also consider accented characters - and punctuation from other languages.
Easy. .contains() is not what you think. It does exact String matching.
"anything".contains("something that's not a regular expression");
Either use this
Pattern p2=Pattern.compile("[A-Za-z]+");//call only once
p2.matcher(txt).find();//call in loop
or this:
for(char ch: "something".toCharArray()){
if(Character.isAlphabetic(ch)){
}
}
Related
After many questions asked by other users this is my first one for which I was not able to find a fitting answer.
However, the problem sounds weird and actually is:
I have had more than one situation in which whitespaces were part of the problem and common solutions to be find on stackoverflow or elsewhere did not help me.
First I wanted to split a String on whitespaces. Should be something like
String[] str = input.split(" ")
But neither (" ") nor any regex like ("\\s+") worked for me. Not really a problem at all. I just chose a different character to split on. :)
Now I'm trying to clean up a string by removing all whitespaces. Common solution to find is
String str = input.replaceAll(" ", "")
I tried to use the regex again and also (" *", "") to prevent exception if the string inludes no whitespaces. Again, none of these worked for me.
Now I'm asking myself whether this is a kinda weird problem on my Java/Eclipse plattform or if I'm doing something basically wrong. Technically I do not think so, because all code above works fine with any other character to split/clean on.
Hope to have made myself understood.
Regards Drebin
edit to make it clearer:
I'm caring just about the "replacing" right now.
My code does accept a combination of values and names separated by comma and series of these separated by semicolon, e.g.:
1,abc;2,def;3,ghi
this gets two time splitted, first on comma, then on semicolon. Works fine.
Now I want to clear such an input by removing all whitespaces to proceed as explained above. Therefore I use, as already explained, String.replaceAll(" ", ""), but it does NOT work. Instead, everything in the string after the FIRST whitespace, no matter where it is, gets removed and is lost. E.g. the String from above would change to
1,abc;
if there is whitespace after the first semicolon.
Hope this part of code works for you:
import java.util.*;
public class Main {
public static void main(String[] args) {
// some info output
Scanner scan = new Scanner(System.in);
String input;
System.out.println("\n wait for input ...");
input = scan.next();
if(input.equals("info"))
{
// special case for information
}
else if(input.equals("end"))
{
scan.close();
System.exit(0);
}
else
{
// here is the problem:
String input2 = input.replaceAll(" ", "");
System.out.println("DEBUG: "+input2);
// further code for cleared Strings
}
}
}
I really do not know how to make it even clearer now ...
The next method of Scanner returns the next token - with the default delimiters that will be a single word, not the complete line.
Use the nextLine method if you want to get the complete line.
I have to check the return value of the method, if it equals the value of a string which is either "Yes" or "No" or should I use a regex which matches with the pattern of the string i.e Yes or No.
So essentialy, I am trying to write in this way
if ((ru.getTest()).equals(("Yes") || (“No”)))
{......
Is it the way , I should proceed or am wrong?
Adding to it.
I would like to post a detailed explanation of my question.
if(ru.getTest().equals("yes/oui") || ru.getTest().equals("no/non")),
It is not just Yes but along with the French literal added to it. So, if (the above condition is met), it should trim the French literal portion and keep only the 'yes' or 'no'..
I tried with this:
if ((ru.getTest()).equals("Yes/Oui") || (ru.getTest()).equals(“No/Non”)) {
Test = ru.getTest().substring(0, Test.indexOf ('/'));
Please correct me If I am wrong.
You can basically just write:
if(ru.getTest().equals("yes") || ru.getTest().equals("no"))
I believe a simple check can be done by using equals and not necessarily using regex. Regex tends to be used for more complex matching scenarios.
Use matches() for regex:
if (ru.getTest().matches("(?i)yes|no"))
If you just want to trim the part after and including a possible slash, you don't even need to check anything first:
String trimmed = ru.getTest().replaceAll("/.*", "");
This will work whether or not there is a slash.
You can write like this.
String s = ru.getTest().toLowerCase();
if(s.contains("yes") || s.contsins("oui")) {
Test = "yes";
} else {
Test = "no";
}
If there are different input, use s.matchs() method for regular expression
Edit 1
I am stuck on a little problem and the guy who I normally turn to is, believe it or not, in Australia on his honeymoon, how inconsiderate is that.
The problem is that I have worked on trying to get a boolean which will either let me know if the file path is correct or not.
The problem is that it always returns false,
I have tried the following sample data
c:\Lingerie\
c:\\Lingerie\\
c:\\
c:\
Edit
This is the input screen that I have developed so far. I have already thought of having extra white spaces, so I already popped in the trim command.
They all have returned false.
Here is the method that I'm using and the code that calls it.
dbFilePath = (text.getText()).trim();
bool03 = busLog.isFilePath(dbFilePath);
System.out.println("The result is " + bool03);
And the method is called is
public boolean isFilePath(String filePath) {
return discreetLog.isFilePathMatched(filePath);
}
And which calls
public boolean isFilePathMatched(String myFilePath){
String regularExpression = "([a-zA-Z]:)?(\\\\[a-zA-Z0-9_.-]+)+\\\\?";
Pattern pattern = Pattern.compile(regularExpression);
return Pattern.matches(regularExpression, myFilePath);
}
I don't know if it is my code or an input error.
The first path of your sample is actually matching the regex correctly.
To match the second and fourth, you have to allow double backslashes. Just add \\\\? on the right of the previous backslashes in your regex.
To match the third and fourth, you need to make the second group optional. Currently it is used with the operator +. Use * instead.
Therefore if you replace your regex with this one:
String regularExpression = "([a-zA-Z]:)?(\\\\\\\\?[a-zA-Z0-9_.-]+)*\\\\?\\\\?";
it will match all your paths, and nothing more.
If you still can not match your sample data, then there is a problem somewhere else in your code. You can try posting an SSCCE.
I've moved into Selenium WebDriver, and still finding the most confusing examples.
I need to be able to read a string (succeeded) run a conditional that asks If specific text is present.
For the sake of this text.
String oneoff = "Jeff is old"
I need to match on Jeff, see code below, as long as Jeff exists in the string, I want to return true. If Jeff doesn't exist, then I will check for oh say 50-75 other names. However the string may contain their name and additional text that cannot be controlled. so I have to do a partial match.
Question 1. am I screwed and will have to build each regex expression in that crazy format that I have been seeing, or am I missing something obvious?
Question 2. Will someone for my sanity please show me the proper way to match on Jeff, with the possibility of text being before and after the name Jeff.
Thank you!
String oneoff = driver.findElement(By.id("id_one_off_byline"))
.getAttribute("value");
System.out.println("One Off is:" + oneoff);
if (oneoff.matches("Jeff")) {
System.out.println("It is Jeff");
} else {
System.out.println("it is not jeff");
}
This is just the functional part of the code,
as Jeff exists in the string, I want to return true
Then you probably should test it with
if (oneoff.contains("Jeff"))
since matches use regex as parameter, so if (oneoff.matches("Jeff")) would return true only if oneoff = "Jeff".
You do not need to use match() for the code you have supplied. Instead use oneoff.equals("String") for string matching. Match() is more for a regex expressions. You could also use oneoff.contains("String") if you want to return true even if the string only exists as a subset of the target string.
if (oneoff.contains("Jeff")) {
System.out.println("It is Jeff");
} else if (!oneoff.contains("Jeff")) {
System.out.println("it is not jeff");
}
I think you should improve your code to be like this, because java probably didn't recognize else string if contained with other "jeff" maybe "JEef" or "JEEF" or even maybe "Jeef "
I hope it works, I used to found same bug like yours and I try this way to overcome it.
I was wondering in Java how I could print a string until it reaches the word "quit" in that string and then instantly stop printing at that point. For instance if the string value was:
"Hi there this is a random string quit this should not be printed"
All that should be printed is "Hi there this is a random string".
I was trying something like this, but I believe it to be wrong.
if ( input.indexOf( "quit" ) > -1 )
{
//code to stop printing here
}
Instead of thinking about the problem as "how to stop printing" (because once you start printing something in Java it's pretty hard to stop it), think about it in terms of "How can I print only the words up to a certain point?" For example:
int quit_position = input.indexOf("quit");
if (quit_position >= 0) {
System.out.println(input.substring(0, quit_position));
} else {
System.out.println(input);
}
Looks like homework, so this answer is in homework style. :-)
You're on the right track.
Save the value of that indexOf to an integer.
Then it's like you have a finger pointing at the right spot - ie, at the end of the substring you really want to print.
That's a hint anyway...
EDIT: Looks like people are giving it to you anyway. But here are some more thoughts:
You might want to think about upper and lower case as well.
Also consider what you are going to do if 'quit' is not there.
Also the solutions here don't strictly solve your problem - they'll print unnecessary spaces too, after the last word ends, before 'quit' starts. If that is a problem you consider String Tokenization or an adapation of the replaceAll solution above to cover for leading whitespace into `quit'.
This has a one-line solution:
System.out.println(input.replaceAll("quit.*", ""));
String.replaceAll() takes a regex to match, which I've specified to be "the literal 'quit' and everything following", which is to be replaced by a blank "" (ie effectively deleted) from the returned String
If you don't mind trailing spaces in your string
int index = input.indexOf("quit");
if (index == -1) index = input.length();
return input.substring(0, index);