Comparing two strings with boolean? - java

I was trying this code writing exercise and I am so lost!
The exercise is:
Complete the method which takes two Strings and one boolean as input. If the boolean is true, this method compares the first two Strings, ignoring case considerations (uppercase/lowercase). Two Strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two Strings are equal ignoring case.
If the boolean is false, this method should compare two Strings and return true if the first String represents the same sequence of characters as the second String, otherwise false.
Note: compareTwoStrings("HELLO", "", false) should return false.
And here is my attempt:
public boolean compareTwoStrings (String a, String b, boolean isIgnoreCase)
{
if (a.equalsIgnoreCase(b)) {
return (isIgnoreCase==true);
}
else if (a.equals(b)) {
return (isIgnoreCase==false);
}
}
It doesn't even compile, but even if it did, I'm sure it wouldn't work.

You're doing it backwards. The subject says: if the boolean is true, then do this, else, then do that. So you should program it the same way:
if (isIgnoreCase) {
return ...
}
else {
return ...
}
The rest is left as an exercise. You should be able to figure it out by yourself.

I think the requested solution is the following method:
public boolean compareTwoStrings(String a, String b, boolean isIgnoreCase)
{
if (isIgnoreCase)
{
return a.equalsIgnoreCase(b);
}
return a.equals(b);
}
Your method das not compile because the Java compiler supposes that unter some circumstances both if conditions evalutes to false. Because of that the compiler can not ensure that at least one return statement is reachable.

This could be the solution for your problem:
public boolean compareTwoStrings (String a, String b, boolean isIgnoreCase){
if (isIgnoreCase)
return (a.toLowerCase()).equals(b.toLowerCase());
else
return a.equals(b);
}

I think this is what you are looking for.
public static void myMethod(String str, String str2, boolean bool) {
if (bool) {
str = str.toLowerCase();
str2 = str2.toLowerCase();
if (str.equals(str2))
System.out.println("strings equal");
}
else {
System.out.println("false condition");
}
}

Related

Return of a palindrome String it is not the expected one. What is the mechanism behind

I am more interested about why does not the return function work. Not about the optimization or my method of thinking.
I have tried a simple program to check recursively if a String is palindrome or not.
package palindrom;
public class PalindromString {
public static boolean isPalindrom(String myText) {
char f = myText.charAt(0);
char l = myText.charAt(myText.length() - 1);
if (f != l) {
return false;
}
else {
if (myText.length() > 1) {
isPalindrom(myText.substring(1, myText.length() - 1));
} else {
return true;
}
}
return true;
}
public static void main(String[] args) {
String text = "cococbc";
System.out.println(isPalindrom(text));
}
}
For the first step , the program takes that first "c" char and the last one and it compares them, then the function is called again , this time with the "ococb" String.
The function takes the "o" char and "b" , it compares them , it sees that they are not equal , it goes to the "return false;" statement , and yet it returns true ?
Can you help me with this ? I really want to understand why it behaves this way :|.
it sees that they are not equal , it goes to the "return false;" statement , and yet it returns true ?
Yes, isPalindrom("ococb") returns false, but when that recursive call returns, you ignore its return value, and therefore isPalindrom("cococbc") returns true. You need to return isPalindrom(myText.substring(1, myText.length() - 1)) in order to fix that.
Besides that issue, you should also change the condition to require myText.length() is at least 3, otherwise you may pass an emptyString` to the recursive call, since you are removing the first and last characters.
if (myText.length() >= 3) {
return isPalindrom(myText.substring(1, myText.length() - 1));
} else {
return true;
}
After you make that change you should remove the final return true;, which will no longer be reachable.
You might also consider adding a check for a null or empty String at the beginning, in order for your method not to throw an exception when called for a null or empty String.

Java - Passing a char variable to a method and returning a boolean?

Hello I am very new to Java, I wanted to know if it were possible to pass a character to a method, and then return true if this character is valid.
I have this method:
public void btnColor(char c) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
// Change button color
}
}
What I would like is to have something like this, although it won't let me do this:
public boolean btnColor(char c, boolean b) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true;
}
}
So it takes a character variable c and returns true if valid. Is there a best practice for this sort of thing?
You can do something like this in order to always return some value. This should be possible and acceptable with Java.
public boolean btnColor(char c, boolean b) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true; // this will return in case of your condition is true
}
return false; // this will return otherwise.
}
try this single line
public boolean btnColor(char c, boolean b) {
return hm.getHiddenWordUpdated().contains(String.valueOf(c));
}
It'll return true or false.
When you have public boolean methodName, it means it MUST return a boolean. Having an "IF" statement in your code, means it can split up to a two possible ways: IF-true and IF-false. You have declared the true statement:
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true;
So you are covering 1/2 of the solution. But what if it is false ? Nothing ? This is why you have problems, so to solve your problem you code should looks like this:
public boolean btnColor(char c) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
return true;
} else {
return false;
}
Now if it is containing the character - it returns TRUE, but if it is not containing it returns FALSE.
All code paths need to return a value.
public boolean btnColor(char c, boolean b) {
if (hm.getHiddenWordUpdated().contains(String.valueOf(c))) {
// add additional code
return true;
}
return false;
}
Alternatively, you could use conditionals in a single line:
public boolean btnColor(char c) {
return (hm.getHiddenWordUpdated().contains(String.valueOf(c))) ? true:false;
}

Not sure how to complete this equals method

Could someone help me with this question please? I've tried looking up other examples of this to find what I need to do and keep running into something called and EqualsBuilder, is that what I need to use? Do I need to have it call on equals again if it satisfies neither of the IFs?
The following code contains a class definition and an incomplete method definition. The equals method is used to compare Buildings.
It is intended to return true if Buildings have the same names and number of floors (but are not necessarily the same Building) and false otherwise.
public class Building {
private String name;
private int noOfFloors;
public boolean equals (Object rhs) {
if (this == rhs) {
return true;
}
if (!(rhs instanceof Building)) {
return false;
}
Building b = (Building) rhs;
// missing return statement
}
}
public boolean equals (Object rhs) {
if (this == rhs) {
return true;
}
if (!(rhs instanceof Building)) {
return false;
}
Building b = (Building) rhs;
// This is what you're supposed to add. It will return true only if both
// object's attributes (name and number of floors) are the same
return this.name.equals(b.name) && this.noOfFloors == b.noOfFloors;
}
The only thing that you have to test for now is the fields of both objects. If they are equal, then you should return true, if at least one of them is not then you should return false.
Since your fields in that case are int and Stringyou can use == for the integer field and .equals() for the String field.
Something like this should do the job just fine:
if(this.name.equals(b.name) && this.noOfFloors == b.noOfFloors){
return true ;
}
else{
return false;
}
After the instanceOf tests you want to compare the fields of the object to the other object. Something like Objects.deepEquals() should do the trick for you nicely.

Method is not returning String?

Doing some beginner problems for Java:
Given two strings, append them together (known as "concatenation") and return the result.
However, if the concatenation creates a double-char, then omit one of the chars, so "abc" and "cat" yields "abcat".
My code:
public static String conCat(String a, String b) {
//abc (c) == cat (c)
if (a.substring(a.length()-1,a.length()) == b.substring(0,1)) {
//return (ab) + (cat)
return a.substring(0,a.length()-2) + b;
//cat (c) == abc (c)
} else if(b.substring(0,1) == a.substring(a.length()-1,a.length())) {
//return (abc) + (at)
return a + b.substring(2,b.length());
} else if (a.equals("") || b.equals("")) {
return a + b;
}
}
I don't understand why Eclipse can't recognise the String returns.
First of all, you are comparing Strings with ==, which compares them by reference. This means that equal Strings might not return true. To avoid this problem, always use .equals() to compare Strings.
Second, keep in mind that your if statements are checked in the order specified. Since you want to check for empty strings first, you should put that one on top.
Third, you have to return something on all codepaths. If all of the if statements are false, you don't return anything. If you add else return a + b; you should get the desired behavior.
Furthermore, I suggest using a slightly different approach:
public static String conCat(String a, String b) {
//If either String is empty, we want to return the other.
if (a.isEmpty()) return b;
else if (b.isEmpty()) return a;
else {
//If the last character of a is the same as the first character of b:
//Since chars are primitives, you can (only) compare them with ==
if (a.charAt(a.length()-1) == b.charAt(0))
return a + b.subString(1);
//Otherwise, just concatenate them.
else
return a + b;
}
}
Note that you can omit the else blocks, since return will end the execution of the method there, so this will also work:
public static String conCat(String a, String b) {
if (a.isEmpty()) return b;
if (b.isEmpty()) return a;
if (a.charAt(a.length()-1) == b.charAt(0)) return a + b.subString(1);
return a + b;
}
actually, it can. but all your return statements are depending on a condition, so there 'll be cases for which you haven't provided a return statement.
in those cases, the method won't return anything, even while it should return a String.
add:
return "";
or
return null;
to the end of your method and try again.

Java Recursive String Comparison with "*" as a Wildcard

I'm writing a recursive method that checks each letter of the string to compare them. I'm having trouble making the "*" character match with any, and act as as many letters as needed. (Making it a wildcard)
I was wondering if someone can give me a hint on the algorithm that would be used?
Here is what I have so far.
public static boolean match(String x, String y) {
return match_loop(x, y, 0, 1);
}
public static boolean match_loop(String a, String b, int i, int s) {
try {
if (a == b) {
return true;
}
if (i >= a.length() && i >= b.length()) {
return true;
}
if (a.charAt(i) == b.charAt(i)) {
return match_loop(a, b, i + 1, s);
}
//(((...A bunch of if statements for my other recursion requirements
return false;
} catch (java.lang.StringIndexOutOfBoundsException e) {
return false;
}
}
public static void main(String[] args) {
System.out.println(match("test", "t*t")); // should return true
}
What I was thinking of doing is adding another arguement to the method, an int that will act as a letter backcounter. Basically I'm thinking of this
if a or b at char(i-s) (s originally being 1.) is a *, recall the recursion with s+1.
and then a few more different ifs statements to fix the bugs. However this method seems really long and repetitive. Are there any other algorithms I can use?
Do not use == for String value comparison. Use the equals() method.
if (a == b) should be if a.equals(b)
If you are using only one character("*") as a wildcard, I recommend you to use regular expression. Such as;
public static boolean match(String x, String y) {
String regex= y.replace("*", "(.*)");
if(x.matches(regex)) {
return true;
}
}
public static void main(String[] args) {
System.out.println(match("test", "t*t")); // should return true
}
I think it is easier to read the code this way.
Have a look at this algorithm. It returns all substrings that match the pattern, so you'll have to check whether the entire string is matched in the end, but that should be easy.
It runs in O(km) time, where k is the number of wildcards and m is the length of your input string.
This book will tell you exactly how to do it:
http://www.amazon.com/Compilers-Principles-Techniques-Alfred-Aho/dp/0201100886
Here's a simple Java implementation that might get you on track: http://matt.might.net/articles/implementation-of-nfas-and-regular-expressions-in-java/
Basically the industrial-strength implementation is a state machine. You deconstruct the regular expression - the string with the '*' in it - and create a graph for it. Then you recursively search the graph, for example in a breadth-first tree search.
Here's some discussion of different ways to do it, that will help illustrate the approach: http://swtch.com/~rsc/regexp/regexp1.html

Categories

Resources