Why the first if statement is failing? - java

Edit: Apologize for confusing some of you, here is little more details.
I am very new to the stackoverflow. So I apologize in advance for a stupid questions.
I came across the below exercise in Udemy and my code is failing. Please help me understand why it is failing?
Description of the exercise:
Write a method shouldWakeUp that has 2 parameters.
1st parameter should of type boolean and be named barking it represents if our dog is currently barking
2nd parameter represents the hour of day and is of the type int with the name hourOfDay and has a valid range of 0-23
we have to wake up if the dog is barking before 8 or after 22 hours so that in that case return true, in all other case return false.
if the hourOfDay parameter is less than 0 or greater 23 return false
public class BarkingDog {
public static boolean shouldWakeUp(boolean barking, int hourOfDay) {
if (hourOfDay < 8 || hourOfDay > 22) {
return true;
} else if (hourOfDay < 0 || hourOfDay > 23) {
}
return false;
}
}

Your first statement fails because you are not checking if it’s barking and conditions for less than 0 or greater than 23.
You need to do the following
public static boolean shouldWakeUp(boolean barking, int hourOfDay) {
if (barking) {
if ((hourOfDay > 0 && hourOfDay < 8) || (hoursOfDay > 22 && hoursOfDay <23)) {
return true;
}
}
return false;
}

Based on the comment:
"method call shouldWakeUp(false, -5) returned a value of "true" but "false" was expected
Its not very weird:
if (hourOfDay < 8 || hourOfDay > 22) {
return true;
}
If hourOfDay = -5, it is
hourOfDay < 8
So it will return True. Since your 2nd if statement checks if it is smaller than 0, this might seems weird. But your 2nd if statement is never reached.
If a number is smaller than 0, it is also smaller then 5.
In order to fix this you can do the following:
public static boolean shouldWakeUp(boolean barking, int hourOfDay) {
if (hourOfDay < 0 || hourOfDay > 23) {
return false;
}
return true;
}
Now we check if the value is less than 0 (so -1,-2,-3,etc) or larger than 23 (so 24,25,26,etc) then we return false. In all other cases we return true (this means between 0 and 23)
Edit: ofc you should use the boolean (barking) you provide in the function to check the time and return accordingly as the assignment describes, but I left that out and think you can fix that yourself.

According to the description provided, your method should return false if the time is in invalid range i.e < 0 or > 23.
In your code, when you give invalid time range say -5, it checks against the first condition and the condition is satisfied because, -5 is lesser than 8. So it returns true. Generally what you should do is always put your guard conditions(which returns false) at first.
So, your code should become as this,
[Edited]
public class BarkingDog {
public static boolean shouldWakeUp(boolean barking, int hourOfDay) {
if (hourOfDay < 0 || hourOfDay > 23) {
return false;
} else if (hourOfDay >= 8 && hourOfDay <= 22) {
return false;
}
return barking;
}
}
Things to consider while writing these kinds of conditions
As said before, try to put all guard conditions at first. Hence it is called as guard. Think it of as a security dog infront of a building. It guards the method by checking all of the invalid checks at first returns the control immediately if it doesn’t satisfy.
Ordering of numerical check should be in ascending order. In your case the values(8) you checked against in your first condition is greater than the values(0). So you have to move this condition up a step. Actually this may confuse you in the beginning when you are using conditions with && or || Boolean operators.
These are some of the tips you can have.

Related

Why won't the method return true when conditions are met?

I'm coding a game in Netbeans using the GUI. In the game, a random amount of stones between 15-30 is generated and the user and the computer take turns removing stones between 1-3 until there are none left. The last player that takes the last stones loses. My problem is that my method (validIn()) won't be used in the playerMove(), so even when the conditions are met, the game doesn't update.
Here is where I think the problem is:
private boolean validIn(int num){
//
return num < 3 || num > 1 || num < totalStone;
}
public void playerMove(){
// Geting the user input
int userIn = Integer.parseInt(txtIn.getText());
// Declaring and assigning a boolean
boolean check = false;
// If the boolean returns true
if (check == true) {
// Subtracting how much the player took from the total amount of rocks
totalStone -= userIn;
// Displaying how many rocks were taken and how many are left
txtOut.setText(txtOut.getText() +"\nYou picked up " +userIn +" stone(s). There are " +totalStone +" stone(s) left.");
}
// Else,
else {
// Assign the boolean check to what the method validIn returns
check = validIn(userIn);
}
}
public void checkWinner(String player){
// If there are no more stones left,
if (totalStone == 0){
// Display a message that says who won
txtOut.setText(txtOut.getText() +"\nThere are no more stones left. "+player +" wins!");
}
}
private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {
//
if (totalStone > 0){
// Display how many rocks there are
txtOut.setText(txtOut.getText() +"\nThere are " +totalStone +" stone(s).");
// The player does their move
playerMove();
// Checking if the computer won
checkWinner("The computer");
// Computer does a turn
computerMove();
// Checking if the player won
checkWinner("The player");
}
//
else if (totalStone == 0){
//
txtOut.setText(txtOut.getText() + "\nThe game has ended.");
}
}
int comIn = (int)(Math.random() * 2) + 1;
// Declaring and assigning a boolean
boolean check = false;
// If number generated is bigger than the total stones,
if (check == true && validIn(userIn) == true){...}
In above code you save the generated number in comIn but you never check comeIn is bigger than total stones in your code.
Then in if condition you are checking that is check equals to boolean true, which is not because you gave check a false value just above and never changed it so it will never run the if loop because inside it the first condition is wrong.
private boolean validIn(int num){
return num < 3 || num > 1 || num < totalStone;
}
Here it is returning true no matter what because the num provided is always less than 3 and greater than 1 if you are playing by your rules
`check = false;
// If the boolean returns true
if (check == true) {...} `
And here again you are setting the value of check false and checking that whether it is true in if loop, which will never run because check will never be true.
For you validIn method you need to think a little about the conditions you have for your method return statement.
The way it is written:
return true if num is ANY value less than 3 like 0, -50, 1, 2 but if it's not then
return true if num is ANY value greater than 1 like 2, 3, 1020, 323243 but if it's not then
return true if num is less than totalStones but if it's not then return false.
The condition to check if num is less than totalStones is never reached because you're using the OR (||) operator. With the use of the first and second conditions you will always be returned true. If the first condition (num < 3) is found to be true then true is instantly returned but if it's not then the second condition (num > 1) is checked and if it is found to be true then true is instantly returned. The third condition (num < totalStones) just can't be reached.
What you want to do is change the || operator to the AND (&&) operator:
return num < 3 && num > 1 && num < totalStone;
return true only if num is less than 3 and num is greater than 1 and num is less than totalStones.
By using the && operator you ensure that all three conditions must be met before true is returned. By saying this now, you can see that only a value of 2 in num will return a true. I think what you meant to use is:
return num <= 3 && num >= 1 && num < totalStone;
This way if num holds 1, 2, or 3 AND either of those values is less than totalStones then return true otherwise false is returned.
In your code, I see boolean Method always return true because you use
|| (OR)
any number less than 3 it will be returned true, or greater than 1 it will return true too.
and in your IF condition I didn't see you set variable check to true but you still have condition check is TRUE therefore that I wonder How can you use this variable to check your condition ?
So how can it jump inside if statement ?
The validIn(userIn) in the playerMove() method would never be reached for some reason. I have to remove the boolean check and change
if (check == true) to if ((validIn(userIn) == true)

Does a simpler representation of this if condition exist?

I used the below conditional statement to ensure that the city name given is of valid length. Length of city should be greater than or equal to 3 and less than or equal to 20.
if(city.length()<3 || city.length()>20) return false;
else return true;
I am told that this conditional statement can be further simplified. Is that right? Then what is the simplified code?
return !(city.length() < 3 || city.length() > 20)
or
return city.length() >= 3 && city.length() <= 20
I simplified your code from IntelliJ IDEA IDE.
Actually it itself suggested to simplify when I used your code there. I recommend you to try IntelliJ IDEA.
return city.length() >= 3 && city.length() <= 20;
If you are already using the IDE, just move the cursor to the code with warning and press ALT+Enter and simplify it.
If city.length() is cheap, then write
return city.length() >= 3 && city.length() <= 20
else you ought to pre-compute city.length() to avoid the potential for two evaluations:
const auto&& /*assuming C++, for Java, you need to use the specific type*/ l = city.length();
return l >= 3 && l <= 20;

Convert this java method without using if/loops

Convert the following without if/loops. You can still use recursion, &&, || etc...
public boolean mystery(int n){
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
I would like hints.
But I've been experimenting around.
We know that true && false == false and only true && true == true
So we must have that
return (n%10 == 7) && ....
Then for the second part, we could either get true or false, and if the second part is true, then our first part being true will result in everything being true, so I am thinking.
return (n%10 == 7) && ...
But I am thinking an issue might be that if n%10 isnt 7 right off that bat everything is false.
In my view, the ternary operator is still pretty much an 'if' statement - but that becomes a semantic debate. You can avoid using it entirely.
return (n % 10 == 7) || (n != 0 && mystery(n/10));
There are many ways: but to give you a start:
if(n == 0){
return false;
}
if(n%10 == 7){
return true;
}
return mystery(n/10)
}
is equivalent to
return n==0 ? false : n%10==7 ? true : mystery(n/10);
is equivalent to
return n!=0 ? n%10==7 ? true : mystery(n/10): false;
is equivalent to
return n!=0 && n%10!=7 ? mystery(n/10) : n!=0;
Was an interesting activity to solve. Solution below with proof of testing till 10k. mystery2 is the method of interest for you.
How I got the solution:
Started printing the results from 0 to 100 and identify the pattern - found the ones starting or ending with 7 would return true and all others false. The first if block which compares with zero is actually encountered by all the numbers which do not qualify reminder 7 rule in any position. Thus, reminder 7 is the only condition to get true result and everything else would enter recursion until it becomes 0 after the unit's position is complete. Equating to 0 is required as we should have a condition that ends the recursion (or ends in StackOverflowException).
public static void main(String[] args) {
for(int i = 0 ; i<=10000; i++){
if(mystery(i) != mystery2(i)){
System.out.println("Mismatch... "+i);
}
}
}
static boolean mystery(int n) {
if (n == 0) {
return false;
}
if (n % 10 == 7) {
return true;
}
return mystery(n / 10);
}
static boolean mystery2(int n) {
return n % 10 == 7 || (n != 0 && mystery2(n / 10));
}

Coding bat simple code logic in JAVA

Coding bat is a website to test the candidate's logic and reasoning abilities using JAVA or Python. I am trying the following problem and am unable to proceed:
Given a non-negative number "num", return true if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2. See also: Introduction to Mod
nearTen(12) → true
nearTen(17) → false
nearTen(19) → true
.
The code I have written is :
{
public boolean nearTen(int num) {
if (num==10 || num==1){
return true;}
else if (num<10){
return false;}
else if ((num+2)%10==0 || ((num-2)%10==0)){
return true;}
else if ((num+1)%10==0 || ((num-1)%10==0)){
return true;}
else{
return false;}
}
}
Can anyone of you please tell my mistake so that I can improve on the same?
You have to check if the modulo of the given number is either less that or equal to 2 (<= 2), or greater than or equal to 8 (>= 8).
You don't have to check for any special values, since there aren't any, they respond to the general logic of the question.
public boolean neatTen (int num) {
if (num%10 <= 2 || num%10 >= 8) {
return true;
} else {
return false;
}
}
If you had to take into account negative values, you would have to use Math.abs() to make the number positive, but that's a very small change to the code.
If you want to have it as a one-liner:
return (num%10 <= 2) ? true : (num%10 >= 8) ? true : false ;
Return true if remainder after dividing by 10 is 0, 1, 2, 8 or 9.
public boolean nearTen (int num) {
if (num%10 <= 2 || num%10 >= 8)
return true;
return false;
}
If I had understood the question right then you just need to use mod(%) and check if the reminder is <= 2 or >= 8.
public static boolean nearTen(int num) {
if (num==10 || num==1){
return true;
}
else if (num<10 && 10-num<2){
return true;
}
else if (num%10<=2 || num%10>=8){
return true;
}
else{
return false;
}
}

Why is my boolean always true?

I made a class for a date and within this class lies the following declarations:
private int year;
private boolean leap = ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0));
public boolean isLeap() {return leap;}
And then (in a different file) within the main method:
String leapStr;
if (dateObject.isLeap()) {leapStr = "";}
else leapStr = "non-";
System.out.printf("Year %d is a %sleap year.", dateObject.getYear(), leapStr);
So, for some reason leapStr is never "non-", even when the year is clearly not a leap year. I have absolutely no idea what the problem could be. Any ideas?
Because the value of leap is calculated once on object creation, and at that moment year is initialized with default value of 0.
You should calculate leap in isLeap method.
You haven't initialized year hence the default value for int will be 0 , this is why yor condition is always returning true (0%400 == 0)

Categories

Resources