How to compare three boolean values - java

Compare three boolean values and display the first one that is true.
Hey guys, I am trying to write a program that compares three boolean values and displays the first true one. I am comparing three words for their length, and it will display the longest. The error that I am getting is that my else tags aren't working. Take a look at the code.
//Check which word is bigger
if (len1 > len2)
word1bt2 = true;
if (len2 > len3)
word2bt3 = true;
if (len1 > len3)
word1bt3 = true;
//Check which word is the longest
if (word1bt2 == true && word1bt3 == true);
System.out.println(wor1);
else if (word2bt3 == true);
System.out.println(wor2);
else System.out.println(wor3);
I have set boolean values for word1bt2, word2bt3 and word1bt3. In eclipse, I am getting a syntax error under the elses in my code above. Any help would be great!

if (word1bt2 == true && word1bt3 == true);
Is wrong, you need to remove the semicolon:
if (word1bt2 == true && word1bt3 == true)
Same for the elses
else (word2bt3 == true);
Is wrong too, it should be
else if (word2bt3 == true)
Side note: boolean values can be used as condition, so your if statements should be
if (word1bt2 && word1bt3) // The same as if (word1bt2 == true && word1bt3 == true)

How to compare three boolean values?
Dont!
If you find yourself needing to compare three variable you may as well cater for any number of variables immediately - there's no point hanging around - do it properly straight away.
public String longest(Iterator<String> i) {
// Walk the iterator.
String longest = i.hasNext() ? i.next() : null;
while (i.hasNext()) {
String next = i.next();
if (next.length() > longest.length()) {
longest = next;
}
}
return longest;
}
public String longest(Iterable<String> i) {
// Walk the iterator.
return longest(i.iterator());
}
public String longest(String... ss) {
// An array is iterable.
return longest(ss);
}

Remove the ; and change it with brackets {}.
if (word1bt2 && word1bt3) {
System.out.println(wor1);
} else if (word2bt3) {
System.out.println(wor2);
} else {
System.out.println(wor3);
}

Issue with the else blocks: use {} insteaad of () to enclose instructions...
Remove the ; at the first if!!!!! - Quite common mistake, with very puzzling results!
//Check which word is the longest
if (word1bt2 == true && word1bt3 == true) { //leave ; and always add bracket!
System.out.println(wor1);
}
else if(word2bt3 == true)
{
System.out.println(wor2);
}
else {
System.out.println(wor3);
}
if you need a condition in an else branch, you have to use if again - plain else won't have such a feature...
ALWAYS use brackets for bodies of if statements, loops, etc!!!
Be extremely careful NOT to use ; in the lines that don't behave well with it:
if statements
for loops
while() {...} loops' while statement

try this, if lenght are equal then s1 is considered as Bigger. Also i have not added null check
public class Test {
public static void main(String[] args) {
String word1 = "hi";
String word2 = "Hello";
String word3 = "Hell";
String Bigger = null;
if(word1.length() >= word2.length() && word1.length() >= word3.length() ){
Bigger = word1;
}else if(word2.length() >= word1.length() && word2.length() >= word3.length()){
Bigger = word2;
}else if(word3.length() >= word2.length() && word3.length() >= word1.length()){
Bigger = word3;
}
System.out.println(Bigger);
}
}

Related

How can I tell my code that it has a "Flush"?

I'm suppose to create a code that recognizes if my hand has the same card faces
public static boolean sameFace(String hand) {
hand = "s9s7s2sQsK";
char f = hand.charAt(0);
if( hand.charAt(0)==hand.charAt(2) && hand.charAt(0)==hand.charAt(4)
&& hand.charAt(0)==hand.charAt(6) && hand.charAt(0)==hand.charAt(8));
return (hand.charAt(0) == hand.charAt(2) && hand.charAt(0) == hand.charAt(4)
&& hand.charAt(0) == hand.charAt(6) && hand.charAt(0) == hand.charAt(8));
sameface = hand;
if (hand==true;)
return (hand==true;) ;
}
As can be seen above, if all positions are the same characters, it comes true(False, if even one isn't the same.) How can I then use the result of that "return" to let my program recognize it has the same faces or not? If that is even possible.
From what i know, based on my code, it's saying "Yes, positions x=y=z are the same" how can I then tell it "Since they are the same, they have the same card faces."
I tried to put this at the end
sameface = hand;
if (hand==true;)
return (hand==true;) ;
Basically I'm trying to say that when the "hand" return statement is true, then samefaces is true. Meaning that the faces are the same. And if it's false it'll return false.
Basically I'm trying to say that when the "hand" return statement is true, then samefaces is true. Meaning that the faces are the same. And if it's false it'll return false.
You do that simply by returning the result of the expression:
public static boolean sameFace(String hand) {
char f = hand.charAt(0);
return f == hand.charAt(2) &&
f == hand.charAt(4) &&
f == hand.charAt(6) &&
f == hand.charAt(8);
}
Or if you want to be friendly to a different number of cards, use a loop:
public static boolean sameFace(String hand) {
char f = hand.charAt(0);
for (int i = 2, len = hand.length(); i < len; i += 2) {
if (f != hand.charAt(i)) {
// Not a match
return false;
}
}
// All matched
return true;
}

Boolean logic for validation is failing

public static boolean isValidReferenceCode(String rc) {
boolean validCode = true;
if (rc.length() != 6 ) {
validCode = false;
} else if ( !Character.isLetter(rc.charAt(0)) ||
!Character.isLetter(rc.charAt(1)) ||
!Character.isDigit(rc.charAt(2)) ||
!Character.isDigit(rc.charAt(3)) ||
!Character.isDigit(rc.charAt(4)) ||
!Character.isLetter(rc.charAt(5))) {
validCode = false;
} else if ( (!rc.substring(5).matches("B")) || (!rc.substring(5).matches("N")) ) {
validCode = false;
}
return validCode;
}
This is my validation method inside a big program, I need a validation that requires the user to input at least 6 characters, first two being letters, next three being digits, and the last character either a "B" or "N" right now it's not doing that. After some trial and error, the first two IF statements seem to be correct and work when I delete the 3rd if statement about substrings, am I using the correct Syntax here? Would really appreciate help!
Find below logic , it will work . Better to use regular expressions .
public static boolean isValidReferenceCode(String rc) {
boolean validCode = true;
String pattern= "^[a-zA-Z]{2}[0-9]{3}[BN]}$";
if (rc.length() != 6) {
validCode = false;
}
validCode = rc.matches(pattern);
return validCode;
}
Another way to solve it is to use the original code with:
} else if ( (rc.charAt(5) != 'B') && (rc.charAt(5) != 'N') ) {
You need both to be misses (i.e., use an && instead of an ||).
Instead of a cascade of ifs and negative logic, you can do the entire test more clearly in a single positive-logic expression:
public static boolean isValidReferenceCode(String rc) {
return
rc.length() == 6 &&
Character.isLetter(rc.charAt(0)) &&
Character.isLetter(rc.charAt(1)) &&
Character.isDigit(rc.charAt(2)) &&
Character.isDigit(rc.charAt(3)) &&
Character.isDigit(rc.charAt(4)) &&
(rc.charAt(5) == 'B' || rc.charAt(5) == 'N');

Second return statement nested in if statement

I am wondering what return str.substring(1,4).equals("bad"); is doing here in the else if(len>=4). I think the if statement is a guard clause but I am not 100%. Can I have an explanation of what exactly is going on here? How is this read to output "false"?
Given a string, return true if "bad" appears starting at index 0 or 1 in the string, such as with "badxxx" or "xbadxx" but not "xxbadxx". The string may be any length, including 0. Note: use .equals() to compare 2 strings.
hasBad("badxx") → true
hasBad("xbadxx") → true
hasBad("xxbadxx") → false
public boolean hasBad(String str)
{
int len = str.length();
if(len == 3 && str.equals("bad"))
return true;
else if(len >= 4)
{
if(str.substring(0, 3).equals("bad"))
return true;
return str.substring(1, 4).equals("bad");
}
else
return false;
}
if(str.substring(0, 3).equals("bad")) is the easy part. "Return true if 'bad' is the beginning of the String.'
return str.substring(1, 4).equals("bad") essentially means, "Return true if 'bad' occurs after the first character, and false otherwise". This is basically a shortcut of
if(str.substring(1, 4).equals("bad")) return true;
else return false;
Because the if already evaluates a boolean (what goes inside of an if results in a boolean value), there's no reason to tell it to return "true if true, else false", you can just return the boolean value directly.
you can try it in other way too, like below one
public static boolean hasBad(String str) {
for (int i = 0; i < str.length() - 1; i++) {
if (str.length()>=3 && str.charAt(0) == 'b' || str.charAt(1) == 'b' ) {
if (str.substring(i).contains("bad")) {
return true;
}
}
}
return false;
}

How can I optimize this code (return statements)?

So while I was typing this question, I found a workaround for a "missing return statement" error. But I still don't think this is the proper way of doing it. As you can see I have some nested if statements. I want both conditions to be met before returning anything, but I had to place the return statements outside of the nested if statements. If the last condition isn't met doubt this should cause much problem since an empty string will be returned, but I just feel as if this isn't the best way of going about doing things.
1st Edit: with my current update, i'm still missing a return statement. I could do the same fix i applied but I feel as if it is innapropriate.
public String findProtein(String dna) {
int start = dna.indexOf("atg");
int stop1 = dna.indexOf("tag", start + 3);
int stop2 = dna.indexOf("tga", start + 3);
int stop3 = dna.indexOf("taa", start + 3);
String subStr1 = dna.substring(start, stop1);
String subStr2 = dna.substring(start, stop2);
String subStr3 = dna.substring(start, stop3);
boolean geneFound = false;
if (subStr1.length() % 3 == 0) {
geneFound = true;
return subStr1;
}
if (geneFound == false) {
if (subStr2.length() % 3 == 0) {
geneFound = true;
}
return subStr2;
}
if (geneFound == false) {
if (subStr3.length() % 3 == 0) {
geneFound = true;
}
return subStr3;
}
if (geneFound == false) {
return "";
}
}
2nd Edit: additional code
private void stopCodon(String gene){
//This prints out the last 3 characters of the gene
String stopCodon = gene.substring(gene.length() - 3);
System.out.println(stopCodon);
}
public void testing() {
String a = "ataaactatgttttaaatgt";
String result = findProtein(a);
stopCodon(result);
}
If it were me, I would edit the following logic
if( subStr1.length() % 3 ==0 ){
geneFound = true;
return subStr1;
}
if(geneFound == false){
if(subStr2.length( )% 3 ==0 ){
geneFound = true;
}return subStr2;
}
if(geneFound == false){
if(subStr3.length( )% 3 ==0 ){
geneFound = true;
}
return subStr3;
}
if (geneFound == false){
return "";
}
To the following using else if statements:
if( subStr1.length() % 3 ==0 ){
return subStr1;
} else if (substr2.length()%3==0){
return substr2;
} else if (substr3.length()%3 == 0) {
return substr3;
} else {
return null;
}
I'm also not sure if String subStr1 = dna.substring(start,stop1); is something you want since an Exception will be thrown if the stop codon doesn't exist, but it would be hard to judge without you giving us additional information.
Added
Kind of saw this coming, but if you look at the description for indexOf
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)
the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
If you want to check if the substring exists, you check if the index is -1
I'm only gonna go through an example for the first substring
int stop1 = dna.indexOf("tag", start + 3);
if(stop != -1) {
return dna.substring(start, stop1);
}
You should start by checking if the start codon exists at all and return null if it doesn't exist immediately, since locations of stop codons are useless without start codons.
Hopefully this helps
if( subStr1.length() % 3 ==0 ){
geneFound = true;
result = subStr1;
}else if(geneFound == false){
if(subStr2.length( )% 3 ==0 ){
geneFound = true;
}
result = subStr2;
}else if(geneFound == false)
if(subStr3.length( )% 3 ==0 ){
geneFound = true;
}
result = subStr3;
}
if (geneFound == false){
result = "";
}
return result;
result is of type String.
However any one of three if statements will return the value. If not fourth if statement will return the value.
You can assign the result to a variable and return it at the end
Why don't you return something like this ?
public String findProtein(String dna) {
String valueToBeReturned = "";
if(condition 1){
valueToBeReturned = "value1"
}
if(condition 2){
valueToBeReturned = "value2"
}
//Rest of the conditions
return valueToBeReturned; //Finally return the specific value
}
How about remove unnecessary block of code?
if (geneFound == false) {
return "";
}
Since you return a value and the boolean is a local variable, it doesn't really matter if you change the boolean value or not in this code. I really don't see a use for it at the time. I simplified the code following your logic!
public String findProtein(String dna) {
int start = dna.indexOf("atg");
int stop1 = dna.indexOf("tag", start+3);
int stop2 = dna.indexOf("tga",start+3);
int stop3 = dna.indexOf("taa",start+3);
String subStr1 = dna.substring(start,stop1);
String subStr2 = dna.substring(start,stop2);
String subStr3 = dna.substring(start,stop3);
if(subStr1.length() % 3 == 0 ) {
return subStr1;
}
if(subStr2.length() % 3 == 0 ){
return subStr2;
}
if(subStr3.length( )% 3 ==0 ){
return subStr3;
}
return "";
}

Recursive Function : Check for palindrome in Java

I have a class that checks whether a string is a palindrome or not. I have two questions.
1) Is this the most efficient way to check for palindrome?
2) Can this be implemented recursively?
public class Words {
public static boolean isPalindrome(String word) {
String pal = null;
word = word.replace(" ", "");
pal = new StringBuffer(word).reverse().toString();
if (word.compareTo(pal) == 0) {
return true;
} else {
return false;
}
}
}
Have a test class to test this... Doubt its needed but here it is anyways if anyone cares to try it out to be able to help me with any of the two questions above...
public class testWords {
public static void main(String[] args) {
if (Words.isPalindrome("a") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Words.isPalindrome("cat") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Words.isPalindrome("w o w") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Words.isPalindrome(" a ") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Words.isPalindrome("mom!") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
thanks in advance for any help and or input :)
To implement a 'palindrome check' recursively, you must compare if the first and last characters are the same. If they are not the same the string is most certainly not a palindrome. If they are the same the string might be a palindrome, you need to compare the 2nd character with the 2nd to last character, and so on until you have strictly less then 2 characters remaining to be checked in your string.
A recursive algorithm would look like this:
public static boolean isPalindrome(String word) {
//Strip out non-alphanumeric characters from string
String cleanWord = word.replaceAll("[^a-zA-Z0-9]","");
//Check for palindrome quality recursively
return checkPalindrome(cleanWord);
}
private static boolean checkPalindrome(String word) {
if(word.length() < 2) { return true; }
char first = word.charAt(0);
char last = word.charAt(word.length()-1);
if( first != last ) { return false; }
else { return checkPalindrome(word.substring(1,word.length()-1)); }
}
Note, that my recursion method is not most efficient approach, but
simple to understand
Marimuthu Madasamy has a more efficient recursive method, but is harder to understand
Joe F has listed an equivalently efficient iterative method
which is the best approach for implementation because it cannot cause a stack overflow error
Here is another recursive solution but using array which could give you some performance advantage over string in recursive calls (avoiding substring or charAt).
private static boolean isPalindrome(final char[] chars, final int from,
final int to) {
if (from > to) return true;
return chars[from] != chars[to] ? false
: isPalindrome(chars, from + 1, to - 1);
}
public static boolean isPalindrome(final String s) {
return isPalindrome(s.toCharArray(), 0, s.length() - 1);
}
The idea is that we keep track of two positions in the array, one at the beginning and another at the end and we keep moving the positions towards the center.
When the positions overlap and pass, we are done comparing all the characters and all the characters so far have matched; the string is palindrome.
At each pass, we compare the characters and if they don't match then the string is not palindrome otherwise move the positions closer.
It's actually sufficient to only check up to the middle character to confirm that it is a palindrome, which means you can simplify it down to something like this:
// Length of my string.
int length = myString.length();
// Loop over first half of string and match with opposite character.
for (int i = 0; i <= length / 2; i++) {
// If we find one that doesn't match then return false.
if (myString.charAt(i) != myString.charAt(length - 1 - i)) return false;
}
// They all match, so we have found a palindrome!
return true;
A recursive solution is very possible but it is not going to give you any performance benefit (and probably isn't as readable).
Can this be implemented Recursively?
YES
Here is example:
public static boolean palindrome(String str)
{
if (str.length()==1 || str.length == 0)
return true;
char c1 = str.charAt(0);
char c2 = str.charAt(str.length() - 1);
if (str.length() == 2)
{
if (c1 == c2)
return true;
else
return false;
}
if (c1 == c2)
return palindrome(str.substring(1,str.length() - 1));
else
return false;
}
My two cents. It's always nice to see the different ways people solve a problem. Of course this is not the most efficient algorithm memory or speed wise.
public static boolean isPalindrome(String s) {
if (s.length() <= 1) { // got to the middle, no need for more checks
return true;
}
char l = s.charAt(0); // first char
char r = s.charAt(s.length() - 1); // last char
if (l == r) { // same char? keep checking
String sub = s.substring(1, s.length() - 1);
return isPalindrome(sub);
}
return false;
}
The simplest way to check palindrome.
private static String palindromic(String word) {
if (word.length() <= 1) {
return "Polidramic";
}else if (word.charAt(0) != word.charAt(word.length() - 1)) {
return "Not Polidramic";
}
return palindromic(word.substring(1, word.length() - 1));
}

Categories