I have a problem where I'm trying to get a parameter to match the format 'Uddd' where 'U' MUST be the letter U and 'ddd' can be any 3 digits from 0-9.
My current code:
//borrow method
public boolean borrow(String borrowerID)
{
//if the borrower ID matches the format 'Uddd'
if (borrowerID.matches("U([0-9]{3})"))
{
//if the status is available
if (status == 'A')
{
this.borrowerID = borrowerID;
this.status = 'O';
this.dateBorrowed = currentDate;
return true;
}
//is not available
else
{
return false;
}
}
//does not match format
else
{
return false;
}
}
For some reason it's not validating properly. When I tried inputting '1' as the parameter, it still returned true.
Is there something I'm missing?
It should not be possible for that method to return true if the input is "1". I can only suggest you ensure you are passing in "1" and that the method is the one being called.
That can be done with a simple debug statement at the top, something like:
System.out.println ("Calling correct function with [" + borrowerId + "]");
at the start of the function.
I'd also suggest a bit of clean-up to make the function easier to code and read, along the lines of:
// borrow method
public boolean borrow(String borrowerID)
{
// Temp debug statement.
// System.out.println ("borrow [" + borrowerId + "]");
// "Not available" or "invalid borrower" means reject request.
if (status != 'A')
return false;
if (! borrowerID.matches("U([0-9]{3})"))
return false;
// Okay to borrow.
this.borrowerID = borrowerID;
this.status = 'O';
this.dateBorrowed = currentDate;
return true;
}
This is a lot cleaner than all those return-else-do-something constructs, and it follows a "fail fast" paradigm.
Some people tend to dislike multiple return points but that's usually because they don't understand why they're considered bad (spaghetti code). With a short function like this, it doesn't pose a problem.
I get good results with your regex : "1" -> false, "UU123" -> false, "U1234" -> false, "U132" -> true.
but you can use \d instead of [0-9] :
borrowerID.matches("U(\\d{3})")
actually that's not possible.when input 1 it won't return true but it return false.may be your status is equal 'A' that should be reason to return true
String borrowerID="1";
boolean matches = borrowerID.matches("U([0-9]{3})");
System.out.println(matches);
output>>
false
if you only want to find is regex match or not then use this .or put a sout and check does status value.definitely it should be A
if (borrowerID.matches("U([0-9]{3})")) {
return true;
} else {
return false;
}
There is no issues with your regex
System.out.println("U888".matches("U([0-9]{3})"));
Output true
System.out.println("1".matches("U([0-9]{3})"));
Output false
Try debug your code, with few breakpoint inside your borrow function
You can also optimize your like
if (borrowerID.matches("U([0-9]{3})") && (status == 'A')) {
this.borrowerID = borrowerID;
this.status = 'O';
this.dateBorrowed = currentDate;
return true;
} else {
return false;
}
I don't understand onething, you are checking the status againist 'A' and inside assignin '0', does it make sense?(Anyway it's upto you)
Related
Hey guys i am trying to use Queue to check for a good bracket and a bad bracket but i am having some problems with the bad brackets.
example:
1.. good bracketed expression
"a*[a+12]",
"a+(b)-c",
"a+{b+8+(b+c)}/a"
2..Bad bracketed expressions
"[", "(}",
"a)[]",
"([)]"--> i keep getting true for this instead of false.
"]["
Here is the code && thanks for the support:
private static boolean check(String string){
Queue<Character> chars = new LinkedList<>();
for (Character charr: string.toCharArray()){
if (charr.equals('{') || charr.equals('[') || charr.equals('(')){
chars.add(charr);
}else if (charr.equals('}')){
return (chars.contains('{') && chars.poll().equals('{'));
}else if (charr.equals(')')){
return (chars.contains('(') && chars.poll().equals('('));
}else if (charr.equals(']')){
return (chars.contains('[') && chars.poll().equals('['));
}
}
return chars.isEmpty();
}
Your problem is that you poll the first element and don't check if the bracket is at the last position, you just check if it is in the array. Use getLast() to check if the open bracket is at the last position and pollLast() to remove the last element.
And don't return something inside the for loop. Just return the result at the end of your function. Your function validate "([)]" as true because it returns after ) and doesn't process more.
private static boolean check(String string){
Queue<Character> chars = new LinkedList<>();
for (Character charr: string.toCharArray()){
if (charr.equals('{') || charr.equals('[') || charr.equals('(')){
chars.add(charr);
}else if (charr.equals('}') && chars.getLast().equals('{')){
chars.pollLast();
}else if (charr.equals(')') && chars.getLast().equals('(')){
chars.pollLast();
}else if (charr.equals(']') && chars.getLast().equals('[')){
chars.pollLast();
}
}
return chars.isEmpty();
}
Sorry about the ugly code. (I'm new coder trying to teach myself Java.)
I was just wondering why the compiler on http://codingbat.com refuses to run this and instead returns the error:
This method must return a result of type String
Here is the code.......................
public String startOz(String str) {
if (str.length() <= 2) {
return str;
}
else if (str.charAt(0) == 'o' && str.charAt(1) != 'z') {
return "o";
}
else if (str.charAt(1) == 'z' && str.charAt(0) != 'o') {
return "z";
}
else if (str.substring(0 , 3).equals("oz")) {
return "oz";
}
}
You need to think about what will be returned if none of those if conditions turns out to be true. Such as if you pass in the string "paxdiablo".
A simple:
return "Stuffed if I know!";
before the function closing brace may be all that's needed, though you'll probably want to use something a little more appropriate :-)
Actually, scratch that. Sit down with a pen and paper and actually write down all the inputs you expect and what the output should be for all of them.
Then think about what the output should be if the input isn't what you expect. Translating that to a series of if statements and a final return statement should then be quite easy.
If you were running this on an actual IDE, like eclipse, you would get the error:
missing return statement
Now you may be thinking,
"But Ruchir, I have 4 return statements already!"
No. Those return statements are all in if statements, meaning if the if statement isn't executed, the compiler won't know what to return. This will throw the null pointer exception.
If you are sure that one of those if statements will be executed, just put an empty return statement:
return;
By making a method without void, you are saying it will return something.
Just add a return statement outside of the if statement.
public String startOz(String str) {
if (str.length() <= 2) {
return str;
}
else if (str.charAt(0) == 'o' && str.charAt(1) != 'z') {
return "o";
}
else if (str.charAt(1) == 'z' && str.charAt(0) != 'o') {
return "z";
}
else if (str.substring(0 , 3).equals("oz")) {
return "oz";
}
return "Your last default String to return.";
}
you can add the last else statement at the end, which will execute when none of your if condition runs, like below -
else if (str.substring(0 , 3).equals("oz")) {
return "oz";
}
else{
return " last string to return" ;
}
if none of your 'if' conditions are met you still need to return a String or simply add the following to the bottom of your method.
return null;
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/
The problem statement goes like this:
We need to create a String data type called emailId
The email ID has to be set using appropriate setter methods.
The validation rules for the email ID check have to be implemented in the main().
Conditions are:
Overall length of the email ID must be >3 and <20.
The emailId must include "#" followed by a minimum of 1 and maximum of 2 "." characters.
The substring before "#" must contain a combination of Upper Case, Lower Case and "_"(underscore) symbols.
The first letter of the email Id must be in Upper Case.
If all the above conditions are valid, it should display "Email ID is valid" or else, it should display an appropriate error message
This is my code:
public class EmailCheck {
String emailId;
public void setEmailId(String emailId){
this.emailId=emailId;
}
public String getEmailId(){
return emailId;
}
public static void main(String[] args) {
EmailCheck em = new EmailCheck();
em.setEmailId("CFDV#gm.a.il.com");
String email = em.getEmailId();
int length = email.length();
boolean flag1 = false;
boolean flag2 = false;
boolean flag3 = false;
boolean flag4 = false;
boolean flag5 = false;
boolean flag6 = false;
boolean flag7 = false;
int count = 0;
//Condition 1
if((length>3 && length<20)== true)
flag1 = true;
else
flag1 = false;
//Condition 2
int temp = email.length();
if(email.contains("#")){
flag2=true;
int a=email.indexOf("#");
for(int i=a;i<temp;i++){
if(email.charAt(i)=='.'){
flag3=true;
count=count+1;
}
}
if(count<1||count>2){
flag4=false;
}
else{
flag4=true;
}
}
else{
flag2 =false;
System.out.println("No # symbol present");
}
//Condition 3
if(email.matches("[A-Z a-z _]+#.*")) //Unable to get the right RegEx here!
flag5 = true;
else
flag5 = false;
//Condition4
if(Character.isUpperCase(email.charAt(0))==true)
flag6 = true;
else
flag6=false;
if(flag1==true && flag2==true && flag3==true && flag4==true && flag5==true &&flag6==true)
System.out.println("Email ID is valid");
else{
if(flag1==false)
System.out.println("Inavlid length of Email ID");
if(flag2==false||flag3==false||flag4==false)
System.out.println("Invalid Position of Special Characters");
if(flag5==false)
System.out.println("Invalid combination for username");
if(flag6==false)
System.out.println("Invalid case of first letter");
}
}
}
I'm not sure of the condition #2(the logic?) and condition #3(the RegExp part). A few of the test cases seem correct, the rest of them are wrong(owing to faulty logic in #2 and esp #3, I think.)
Please, tell me what changes have to be done here to get the right output.
Thanks!
If you insist on using regex you can use this but without validating properly you could be in for all kinds of trouble
static Pattern emailPattern = Pattern.compile("[a-zA-Z0-9[!#$%&'()*+,/\-_\.\"]]+#[a-zA-Z0-9[!#$%&'()*+,/\-_\"]]+\.[a-zA-Z0-9[!#$%&'()*+,/\-_\"\.]]+");
public static boolean isValidEmail(String email) {
Matcher m = emailPattern.matcher(email); return !m.matches();
}
Or alternatively you could use
public static boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}
Which is a core java utility which would be better...
Note that neither of these will guarentee an address is actually valid, just that it is correctly formed and so hypothetically could exist
String email_regex = "[A-Z]+[a-zA-Z_]+#\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
String testString = "Im_an_email#email.co.uk";
Boolean b = testString.matches(email_regex);
System.out.println("String: " + testString + " :Valid = " + b);
will check for the last three constraints which you can then combine with
string.length()>3 && string.length()<20
Overall length of the email ID must be >3 and <20.
You have this part fine - a pair of length checks. Things to consider:
You don't need if (condition == true), just if (condition).
If this fails, you can stop processing the email and just display the error. The same applies for all your other error conditions.
The emailId must include "#" followed by a minimum of 1 and maximum of 2 "." characters.
Check for the # sign first and get the index. Once you have that, you can split the string. You can then split the substring on periods and count them - you want two or three.
There's probably a regex that would do this as well.
The substring before "#" must contain a combination of Upper Case, Lower Case and "_"(underscore) symbols.
You can use this approach to ensure your regex must match each part. As it stands, I believe your regex will work if there are caps, lowercase, or an underscore instead of checking for all three.
The first letter of the email Id must be in Upper Case.
Same comments as for the first part, drop the == true and short circuit the method if it fails.
So I need to create a method isValidDNA which works like this:
public boolean isValidDNA()
Returns true if the DNA is valid, i.e, only contains the letters,
A,T,C,G (in uppercase) and at least one of these characters.
All I could think of was this, which apparently doesn't work:
public boolean isValidDNA(){
for (int i=0;i<dna.length();i++){
if (dna.charAt(i)=='A' || dna.charAt(i)=='T' || dna.charAt(i)=='C' || dna.charAt(i)=='G' ){
return true;
}
return false;
}
}
You can use this regular expression:- [ATCG]+ In code this could look like this:
public boolean isValidDNA(){
return dna.matches("^[ATCG]+$")
}
You make a return statement immediately, which will exit during the first iteration and only check the first character.
You need to store this information in a boolean and return it after you've checked the whole string:
public boolean isValidDNA(String dna){
Boolean result = true;
// Add an extra check for the "at least one character" thing.
for (int i=0; i<dna.length(); i++){
if (dna.charAt(i)!='A' && dna.charAt(i)!='T' && dna.charAt(i)!='C' && dna.charAt(i)!='G' ){
result = false;
}
}
return result;
}
However, you would be better off using regular expressions for these problems.
Try it this way:
public boolean isValidDNA(){
boolean res = true;
for (int i=0;i<dna.length();i++){
if ((dna.charAt(i) != 'A') && (dna.charAt(i)!='T') && (dna.charAt(i)!='C') && (dna.charAt(i)!='G') ){
res = false;
break;
}
}
return res;
}
if your startpoint is that the DNA is valid, it's much more easy to test if it's really so. You only have to test each char of your dna and can stop by the first entry that doesn't satisfy your if-statement.
Using your way, you've almost got it.
Right now, you return true if you find one that's OK, and only return false if all are wrong. You can negate your if condition, and return false as soon as you find one that's not OK, and only return true if all are fine.
I'll leave the coding part up to you.
As others pointed out, regex will be a cleaner solution here.
You can try this implementation.
First declare a constant:
private static final String bases = "ATCG";
And then use it in the method like this:
public boolean isValidDNA() {
boolean isValid = true;
for (char c : dna.toCharArray()) {
if (bases.indexOf(c) < 0) {
isValid = false;
break;
}
}
return isValid;
}
Scanner sc = new Scanner(System.in);
System.out.print("Enter a DNA sequence: ");
seq=sc.nextLine();
if(seq.matches(".*[^ATCG].*")){
System.out.println("Not a valid sequence.");
System.exit(0);
}
This regular expression works so that only sequences containg A,C,T or G with no other charcters, spaces, etc included will continue