Functioning if statement, improving it - if-statement

if (dog.equalsIgnoreCase("yes")) {
drink.don.setCost(8.75);
drink.don.getType();
drin.l.add(drink.don.getType());
drink.c.add((double) coke.don.getCost());
cokeprice = coke + fanta.don.getCost();
else if (dog.equalsIgnoreCase("no"))
else catch(IllegalArgumentException iae) {
System.out.println("requires yes or no");
}
}
Ignore the stupid naming conventions had to change them, incase any class mates decided to steal anything ;p
I'm trying to get my if statement to allow the user input yes and do a condition, then if "no" has been entered then nothing happens just moves onto the next statement, then anything else is illegal and the program crashes.

I don't like throwing exceptions, especially if I expect that the user might type in something that I don't want. I'd rather do something like
if (userInput.equalsIgnoreCase("Yes")) {
// do yes
}
else if (userInput.equalsIgnoreCase("No")) {
// do no
}
else {
// Sorry, invalid input
}

I don't know what language you are using, nor do I know what any of the methods you are using do, but here is an example of a similar statement in C#.
First, use a method to convert the user input to a true or false (boolean) value:
public static bool IsYes (string userInput)
{
if (userInput == "yes')
{
return true;
}
else if (userInput == "no")
{
return false;
}
else
{
throw new CustomException();
}
}
Next, you can take the result of IsYes() and use it for the if else statement:
if (IsYes(userInput))
{
// code you want to execute if "yes"
}
else
{
// code you want to execute if "no"
}
Hopefully this code will give you an idea of how to use if-else statements, but in the future please explain your question more clearely. Remember, this is C#, so although if statements are similar in almost all languages some of the other code will differ. Also, this is just an example, it won't do anything on its own.

Related

Whats the best way to account for every possibility for two booleans

So I have run into this a few times now and was wondering if there is some kind of smart way to do it? I mostly program in C#, C++ and JavaScript so a cool method in any of those languages would be helpful. I'm primarily looking for speed, but if there are other things I should be cognisent of I'd love to know about them.
I'll show you an example of what I write generally:
if(bool0 || bool1)
{
if(!bool0)
{
if(!bool1)
{
// do stuff
}
else
{
// do stuff
}
}
else
{
if(!bool1)
{
// do stuff
}
else
{
// do stuff
}
}
}
The other thing I'm wondering is, could this be done in a switch statement? Probably not best practice but I thought it was an interesting idea.
You have 4 cases:
if(bool0 && bool1)
else if(!bool0 && bool1)
else if(bool0 && !bool1)
else if(!bool0 && !bool1)

do ... while loop not breaking c++

currently I'm having problems with this do ... while loop.
do {
// program code here
cout << "Would you like to run the program again?(yes/no)";
bool exit = false;
string strexit;
do {
getline(cin, strexit);
if (strexit == "no") {
exit = false;
break;
}
else if (strexit == "yes") {
exit = true;
}
else {
cout << "Enter yes to rerun the program, and no to exit.\n";
};
} while (!exit);
system("cls");
} while (exit);
return 0;
}
I researched online, how to break out of do ... while loops, and it's when the condition is true, it loops back again, but if its false it exits.
So if you look at the code, if the user types in no, it sets exit = false, which takes it out of the bigger do while loop, where the break takes it out of the current do while loop.
If the user enters yes, it changes exit to true, which breaks it out of the current do ... while loop, but it doesn't break out of the second.
My question is, (or what I need help with) is that when the user inputs 'no', it cannot exit the do ... while loops, and I'm severely confused as to why. (It loops back to the beginning of the program.)
In the (shortened) code
do
{
bool exit = false;
// ...
} while (!exit);
you actually have two different symbols named exit. Inside the loop you have the variable. Outside of the loop, and used for the condition, you have the function std::exit. Which will be plain exit if you have using namespace std;.
The function exit when used in the condition will decay to a pointer to the function, and it will never be "false". So the condition !exit is always true and you have an infinite loop.
To solve this there are two things you need to do:
Learn that using namespace std; is very bad practice
Move the variable exit to be defined outside the loop. And you should really rename to something more descriptive it as well (the word "exit" is a little bit to general).
I think #SomeProgrammerDude has given excellent advice that's well worth following--but I'd go a step further, and advise moving the code to get the user's response into a separate function so you can more easily reason about each part of the code in isolation:
bool check_for_exit() {
std::string prompt = "\nDo you want to exit the program? ";
std::string strexit;
do {
std::cout << prompt;
std::getline(std::cin, strexit);
prompt = "\nPlease enter yes or no";
} while (strexit != "yes" && strexit != "no");
return strexit == "yes";
}
Then you use that function in the code that does the real work, something on this order:
do {
whatever();
} while (!check_for_exit());
It seems to me that this approach helps avoid many of the problems you encountered in your code.

If-else loop to find solution

My code is:
#include<stdio.h>
void main(void)
{
float timeLeavingTP;
int transitNumber;
float transitTime;
printf("Please enter the time leaving TP.\n");
scanf_s("%f",&timeLeavingTP);
printf("Please enter bus number.\n");
scanf_s("%d",&transitNumber);
if(timeLeavingTP==1.00)
{
if(transitNumber==27)
{
transitTime=1.56;
}
else if(transitNumber==8);
{
transitTime=1.39;
}
}
if(timeLeavingTP==6.30)
{
if(transitNumber==27)
{
transitTime=7.32;
}
else if(transitNumber==8)
{
transitTime=7.29;
}
printf("The time reached home is %f\n",transitTime);
}
}
After debugging i got
Please enter the time leaving TP
1.00
Please enter bus number
27
Please enter to continue...
My question is How do i adjust the program to make it look like the one below instead. What kind of error did i commit?
Please enter the time leaving TP
1.00
Please enter bus number
27
The time reached home is 1.56
Thanks for the help in advance!
Hi guys after including == i still got the same for my debugging? Is there something else that i did wrong?
Part 1: = vs ==
Note that:
if(timeLeavingTP=1.00)
Does not do what you expect. It assigns timeLeavingTP with 1.00.
You probably want:
if(timeLeavingTP==1.00)
Additionally, note that this error occurs 6 times in your program.
Part 2: comparing floating point numbers
Your code might work in this case, but I'm not 100% sure if it will or not. It's often difficult to directly compare 2 floating point numbers, because of the inaccuracy of storing them (for example, 0.1 is usually not representable in floating point).
Most people solve this problem in one of a few ways:
Test a range around the number.
Convert to some fixes width format. Perhaps you could store the number as an integer, knowing that it's representation is actually 0.01 * the stored number.
In this case, you could actually just store the information as strings, and compare those.
Part 3: conditionals
To write a proper conditional, it should look like:
if (condition) {
...
} else if (condition) {
...
} else if (condition) {
...
} else {
...
}
You can certainly nest conditionals as well:
if (condition) {
if (condition) {
...
} else {
...
}
} else if (condition) {
...
}
Your code, for example, messes this up when you do:
}
else(transitNumber=8);
{
transitTime=1.39;
}
Note that the else statement does not accept a conditional after it.
Part 4: excessive semicolons
Additionally, note that after the else and if statements there are no semicolons. The semicolons only appear within the braces. So this statement:
if(timeLeavingTP=6.30);
While semantically valid, does not do what you expect. You actually want to remove that semicolon.
if(timeLeavingTP == 1.00)
{
if(transitNumber == 27)
{
transitTime=1.56;
}
else if(transitNumber == 8)
{
transitTime=1.39;
}
}
else if(timeLeavingTP == 6.30)
{
if(transitNumber == 27)
{
transitTime == 7.32;
}
if(transitNumber ==8)
{
transitTime=7.29;
}
}
printf("The time reached home is %f\n",transitTime);
}
if(transitNumber=27)
{
transitTime=1.56;
}
else(transitNumber=8);
{
transitTime=1.39; //this line is executed all the time
}
This code is completly invalid!
First, you do not compare anything... transitNumber = 27 is an assignment.
Second else(transitNumber=8); again this is an assignment and it should be else if(...). Also ; at the and means that transitTime = 1.39(inside bracket) will always happen, even if transitNumber != 8
Change
if(timeLeavingTP=1.00)
to
if(timeLeavingTP==1.00)
so that you can compare timeLeavingTP correctly.

c++ function check true condition

I make a function call and when it returns false, I continue to check indefinitely until it returns true. Is the following code is fine?
while(true)
{
bool result = func();
if(result == false)
continue;
else
break;
}
How about getting rid of the break and continue. It is not considered very nice to use them (especially when not required):
bool result;
do
{
result = func();
if(result == false) {
// Supposedly you want to do something here...?
}
} while(result == false);
Of course you can use ! instead of false to save some bytes in your source code. But I suppose that does not really matter at this point.
You could do that, but why not just:
while(!func())
{
// do what you want to do...
}
Why not use
while (!func());
instead? Some folk don't like to see an empty while and may therefore prefer #dwxw's solution.
You can make it shorter.
do
{
} while (!func());

Should conditions test for positive or negative results?

Sorry if the title is rather ambiguous, I was not sure how to word it.
Is it better to phrase a condition such that the outcome you don't want enters the if statement then you exit the function or should I test for the outcome I do want and follow the statement with my code.
Maybe some examples would help:
What I mean by testing for negative result:
if(myObject == null) {
return;
}
//do whatever with myObject
What I mean by testing for positive result:
if(myObject != null) {
//do whatever with myObject
}
Sorry, if someone can word it better than me please do.
I personally prefer the first method of checking if the object is null then immediately returning. It allows the "real code" to stay unindented, linear, and can prevent many nested if statements, which I find to be more readable.
Otherwise, both ways are valid and will have the same outcome. Choose whichever works best in your situation (which can depend on any else or else if statements).
Here's a good example:
if (object1 == null) {
return;
}
// do some stuff
if (object2 == null) {
return;
}
// do some stuff
if (object3 == null) {
return;
}
Opposed to:
if (object1 != null) {
// do some stuff
if (object2 != null) {
// do some stuff
if (object3 != null) {
// do some stuff
}
}
}
I find the first one to be much more readable.
Where there is a valid action that can be taken on satisfying a positive condition, such as logging that a result set is empty, or that a variable was not assigned to, then it is better to use positive conditions. APIs can help here, such as Apache Commons StringUtils isNotBlank(), when you are testing strings. However, sometimes the cleanest thing is to go for a negative test, for example only allowing processing to proceed where a variable is non-null.