java boolean method not returning true/false? - java

In an example in class we were given this method as part of a bigger problem:
public boolean isWinner()
{
return ((points == 4) || (score == 4));
}
My impression of boolean type methods was that they HAVE to return true/false like "return true;" In this example there is no where indicating whether it is returning true/false so if points == 4 does it return true? and if score ==4 does it return false? or is it if either are true then the entire return statement is true?

If either points == 4 or score == 4 is true, the whole thing will be true. All boolean expressions evaluate down to either true or false.
This expression:
return ((points == 4) || (score == 4));
Will either return true or false.

|| is the OR operator. Which for two expressions has the following truth table:
T T = T
T F = T
F T = T
F F = F
So if both points and score are false then the function will return false. Otherwise it will return true.

return ((points == 4) || (score == 4));
Execution of above will result in return true or return false
From specification.
The value produced by the == operator is true if the value of the left-hand operand is equal to the value of the right-hand operand; otherwise, the result is false.
also read about || operation in specification I hope that will clear your doubts

This
return (points == 4) || (score == 4);
is the same as
boolean ret = (points == 4) || (score == 4);
return ret;
which is the same as
if (points == 4) return true;
if (score == 4) return true;
return false;

You should take a look at the Java truth tables for || and &&. This will help give you an understanding of boolean results.
As your question stands, it will return true if either of those statements are true and false if they are both false.

There is only one exception in that code.
In the case that points/score are Integer referencing null, would cause an exception.
public class Snippet {
private Integer points;
private Integer score;
public boolean isWinner() {
return ((points == 4) || (score == 4));
}
public static void main(String[] args) {
System.out.println(new Snippet().isWinner());
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at snippet.Snippet.isWinner(Snippet.java:8)
at snippet.Snippet.main(Snippet.java:13)

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;
}

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 to declare a boolean and only gives true if the first and the last character is "a" [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
Given a string personName, I'm trying to create a boolean condition2 equal to the condition
the first or last letter in personName is 'A' (case-insensitive). e.g., 'aha' or 'A'
Here's what I've tried so far:
boolean condition2;
if (personName.charAt(0) = "a" || personName.charAt(personName.length()-1) = "a") {
condition2 = true;
} else {
condition2 = false;
}
char type in Java is a character so wouldn't you be looking for something like this?
boolean condition2;
if((personName.charAt(0) == 'a' || personName.charAt(0) == 'A') &&
(personName.charAt(personName.length()-1) == 'a' || personName.charAt(personName.length()-1) == 'A'))
{
condition2 = true;
}
else{
condition2 = false;
}
For your first question where first and last character of a String should be 'a'
boolean condition1 = false;
if(personName.charAt(0) == 'a' && personName.charAt(personName.length()-1) == 'a') {
condition1 = true;
}
For your second condition where variable should be true only if age is in the range [18,24]
boolean condition2 = false;
if(personAge >=18 && personAge <=24) {
condition2 = true;
}
You can do it this way except comparison operator is == and you compare characters, not String.
So right way would be:
Character.toLowerCase(personName.charAt(0)) == 'a'
See, double equals and single quote.
use single quote for data type char. and convert it to lower case, so that it allow whether it's upper case or lower case.
Also use == when comparing if it's equal. this = sign, is for assigning value
if(Character.toLowerCase(personName.charAt(0)) == 'a' ||
Character.toLowerCase(personName.charAt(personName.length()-1)) == 'a')
it will look like this
boolean condition2;
if(Character.toLowerCase(personName.charAt(0)) == 'a' || Character.toLowerCase(personName.charAt(personName.length()-1)) == 'a')
{
condition2 = true;
}
else{
condition2 = false;
}
Your problem can be solve in this manner;
public static void main(String[] args) {
String s = "bsdadasd";
boolean condition2;
System.out.println(check(s.toLowerCase().charAt(0),s.toLowerCase().charAt(s.length()-1)));
}
public static boolean check(char a,char b){
return (a == 'a' || b == 'a');
}
You can pass the two characters as parameters for a method where it return true or falsedepending on the condition.
Since both characters are irrelevant of its case first made them to lowercase. toLowerCase() then passed the char at 0 and char at last.
The return statement will return the true or false to you.
And also use == to check if similar = means assigning.
It is circuitous to write
boolean b;
if (some boolean expression)
b = true;
else
b = false;
Much simpler to write
boolean b = some boolean expression;
For reasons I don't understand, there is a widespread reluctance to write a boolean expression (as distinct from the simple literal values true/false) outside an 'if' statement.
And don't get me started on if (b == true)

My equals method output is true while it should be false

I am writing a code and am following all instructions given to me. All the codes and methods look fine when I run the program but the equal method! Based on the instructions, I am supposed to get false when the tested asks if point (a, b)---(c, d) is equals to (e, f)---(g, h), but I get true. Can Anyone give me an idea where I am doing wrong?
Thank you in advance!
/**
* The equals method should return true if the given object is equal to the
* the Object passed in. Note that this method receives an Object; there is
* a particular way that this method should be implemented (see notes from class).
*
* Notice that two Segments are equal even if their endpoints are swapped
* i.e.: (1, 2)---(3, 4) == (3, 4)---(1, 2)
*/
public boolean equals(Object obj) {
//if (obj instanceof Segment) {
//Segment other = (Segment) obj;
//return p1 == other.getP1() && p2 == other.getP2();
//}
//else {
//throw new IllegalArgumentException("undefined");
//}
if(obj == null)
return false;
if(this == obj)
return true;
if(!(obj instanceof Segment))
return false;
else if(obj.getClass() != this.getClass()){
return false;
}
else
{
Segment S = (Segment)obj;
if(this.getP1() == S.getP1() &&
this.getP2() == S.getP2());
return true;
//else if(obj.getP1() != this.getP1() &&
// obj.getP2() != this.getP2());
// return false;
}
}
if(this.getP1() == S.getP1() &&
this.getP2() == S.getP2());
^
Take out this semicolon.
Then you will also need to return a value if the if statement isn't met.
Edit
Currently your if statement is serving no purpose. Take out the semicolon so that the following return statement is qualified by the if. Then after that add a return false that will be applied if the if statement isn't met.
Like this:
if (this.getP1()==S.getP1() && this.getP2()==S.getP2()) {
return true;
}
return false;
Or, put more simply:
return (this.getP1()==S.getP1() && this.getP2()==S.getP2());

java - recursive program for judging the validity of expression syntax (beginner)

I'm just learning java, and I have an assignment where I have to write a program that checks the validity of expressions about sets. Valid expressions are capital letters, an expression with a tilde in front, and can be combined using + and x as well as with parentheses. I've written a program that almost works, but I can't figure out how to get the binary operators to work with the parentheses.
It may also be that I have approached the problem in the wrong way (trying to validate from left to right, ignoring everything to the left once it's been validated). I can use any help I can get about writing recursive programs for this sort of problem; that is, if you have any pointers for a better way of approaching the problem, that would be incredibly helpful.
For reference, here is the code that I have:
public static boolean check(String expr) {
char spot;
int close=0;
expr = expr.trim();
//base case
if (expr.length() == 1 && expr.charAt(0)>= 'A' && expr.charAt(0) <= 'Z')
return true;
if (expr.charAt(0) == '~') {
if (expr.charAt(1) == 'x' || expr.charAt(1) == '+' || expr.charAt(1) == ')')
return false;
return check(expr.substring(1));
}
if (expr.indexOf('x') > 0 && expr.indexOf('x') > expr.indexOf(')')) {
int x = expr.indexOf('x');
if (check(expr.substring(0, x)) && check(expr.substring(x)))
return true;
}
if (expr.indexOf('+') > 0 && expr.indexOf('+') > expr.indexOf(')')) {
int plus = expr.indexOf('+');
if (check(expr.substring(0, plus)) && check(expr.substring(plus+1)))
return true;
}
if (expr.charAt(0) == '(') {
close = findEnd(expr.substring(1));
if (close < 0)
return false;
if (check(expr.substring(1,close)) && check(expr.substring(close+1)))
return true;
}
return false;
}
I'm not sure why your code is that complex. Recursion for this is pretty simple overall; here's what I'd do:
public static boolean check(String str) {
if(str.equals("")) return true;
if(str.charAt(0).isAlphaNumeric() || str.charAt(0) == '(' || str.charAt(0) == ')') return check(str.substring(1));
return false;
}
Your edge cases are if the string is empty; if this is the case, then the string is valid. If the character doesn't match what you're looking for, return false. Otherwise, check the next character.

Categories