Why am I getting an 'Else without previous if' error within a for loop? - c++

I'm new to C++ and have been staring at my (probably abysmal) code for a while and can't figure out what's off about it.
I'm trying to loop through a few iterations of if and else statements and must be doing something grammatically incorrect - as it shows compiler errors of 'else without a previous if'
This is for a class and I'm trying to work it out, but if you see something obvious that I am overlooking I would love to know.
Thank you!
for (i = 0; i < iterationsNum; i++){
if (charlieAlive == 0) // Aarron's shot
{
if (aaronShot() == 1)
charlieAlive = 1;
}
else (charlieAlive == 1 && bobAlive == 0);{
if (aaronShot() == 1)
bobAlive = 1;
}
else (charlieAlive == 1 && bobAlive == 1 && aaronAlive == 0);{
cout << "Aaron is the Winner!\n";
totalShot++;
aaronCounter++;
}
continue;
if (charlieAlive == 0 && aaronAlive ==0) // Bob's shot
{
if (bobShot() == 1)
charlieAlive = 1;
}
else (charlieAlive == 1 && aaronAlive == 0);{
if (bobShot() == 1)
aaronAlive = 1;
}
else (charlieAlive == 1 && aaronAlive == 1 && bobAlive == 0);{
cout << "Bob is the Winner!\n";
bobCounter++;
totalShot++;
}
continue;
if (charlieAlive == 0 && bobAlive == 0) // Charlie's shot
{
bobAlive = 1;
}
else (charlieAlive == 0 && bobAlive == 1 && aaronAlive == 0);{
aaronAlive = 1;
totalShot++;
}
else (charlieAlive == 0 && bobAlive == 1 && aaronAlive == 1);{
cout << "Charlie is the Winner!\n";
}
continue;

else doesn' take any condition, but you've written this:
else (charlieAlive == 1 && bobAlive == 0); //else : (notice semicolon)
which doesn't do what you intend it to do.
You want to do thos:
else if (charlieAlive == 1 && bobAlive == 0) //else if : (semicolon removed)
Notice the difference.
Also, there can be at most one else block, associated with an if block Or a chain of if, else-if, else-if blocks. That is, you can write this:
if (condition) {}
else {}
Or,
if (condition0) {}
else if (condition1) {}
else if (condition2) {}
else if (condition3) {}
else if (condition4) {}
else {}
In any case, else block is always the last block. After that if you write another else block, that would be an error.
Apart from that you also have a semicolon at wrong place. Fixed that also:
else (charlieAlive == 1 && bobAlive == 0); <---- remove this semicolon!
Hope that helps.
Pick a good Introductory C++ Book. Here are few recommendations for all levels.
The Definitive C++ Book Guide and List

There are several problems I see here:
There are semicolons in your else statements - these aren't supposed to be there
You have multiple else clauses for a single if. Use 'else if' when you are evaluating another condition - else is the catch-all for when no conditions are met
I highly recommend proper indenting and consistent brace usage - not doing this isn't necessarily an error, but it will make it much easier to notice errors.

you cant put condition statement in else statement
correct for all else statements
like in else (charlieAlive == 1 && bobAlive == 0);
else is simply the alternative flow of if - i.e.
if(condition) // if this fails go to else part
{
--- // if condition true execute this
}
else{
--- // will run when condition in if fails
}
so you don't have to put condition for else statement
Edit
where as else if takes condition as well
seems you wanted to do this
else if(your condition statements) // Note: no semicolon at the end

Related

Multiple if statements are having single else part

I have four if conditions and for all four conditions else is single.
I four conditions are true they have their own result to be executed but if they all fail they should enter in else part which common for all and can be executed only once.
For example, for save button all four fields should have values if not, respective field will throw an error and stop saving form further.
c.save = function () {
if(a == '' || a == undefined){
throw an error for a
}else
if(b == '' || b == undefined){
throw an error for b
}else
if(c == '' || c == undefined){
throw an error for c
}else
if(d == '' || d == undefined){
throw an error for d
}else
c.data.save = true;
}
You could use a bool to check if all if statements have failed.
bool someBoolean = true;
if(a == true) {
// code to execute
someBoolean = false;
}
else if(b == true) {
// code to execute
someBoolean = false;
}
else if(c == true) {
// code to execute
someBoolean = false;
}
else if(d == true) {
// code to execute
someBoolean = false;
}
// check if the bool is still true
if(someBoolean) {
// code to execute if all if statements failed
}
And then all you have to do is set the bool back to it's original state to use it again.

gtkmm keyboard events skip

Is there a way to cancel key_release event on certain conditions?
I try to explain better...I want that in an entry I can only insert numbers, if I insert another character this will be skipped.
.h file
bool on_value_change(GdkEventKey* key_event);
.c++ file
m_TxtDiversi1->signal_key_release_event().connect(sigc::mem_fun(*this, &MainWindow::on_value_change));
bool MainWindow::on_value_change(GdkEventKey* key_event)
{
if((key_event->keyval >= 48 && key_event->keyval <= 57) || (key_event->keyval >= 65456 && key_event->keyval <= 65465) || key_event->keyval == 65454)
{
std::cout << "1ui" << std::endl;
return true;
}
return false;
}
can somebody hel me please? Thanks a lot in advance.
I found a solution
m_TxtDiversi1->signal_key_press_event().connect(sigc::mem_fun(*this, &MainWindow::on_value_change), false);
bool MainWindow::on_value_change(GdkEventKey* key_event)
{
if((key_event->keyval >= 48 && key_event->keyval <= 57) || (key_event->keyval >= 65456 && key_event->keyval <= 65465) || key_event->keyval == 65454)
{
std::cout << "1ui" << std::endl;
return false;
}
return true;
}

Arduino Autonmous car if statements (ultrasonic)

I have run into a problem while creating the if statements for the autonomous car. The car skips most of the if statements and immeaditly goes to the else statement. The sensors give of the right values. Is it because i use "else if" statements or something else? The car is supposed to react to its surroundings, so i had to give it many if statements as possible. But instead it just does the last bit where it goes backwards waits goes backwards left and backwards right. So my question is do i have to add more if statements so it reacts better to its surroundings or is there more to it? Here is the code of the if statements:
if (sensors[0] >= 50 ) { //if the distance of the front sensor is greater than 50cm, than set Fwd true. Otherwise its false.
Fwd = true;
} else {
Fwd = false;
}
delay(50);
if ((Fwd == true) && (sensors[1] > 50) && (sensors[2] > 50)) {
fwd();
} else if ((Fwd == true) && (sensors[1] < 50)) {
fwdRight();
} else if ((Fwd == true) && (sensors[2] < 50)) {
fwdLeft();
} else if ((Fwd == false) && (sensors[1] < 50) && (sensors[2] < 50)) {
Stp();
} else if ((Fwd == false) && (sensors[1] < 50)) {
bwdRight();
} else if ((Fwd == false) && sensors[2] < 50) {
bwdRight();
} else {
Stp();
delay(1000);
bwd();
delay(500);
bwdLeft();
delay(500);
bwdRight();
}
Start by tidying up your code, and it may be obvious where things may be going wrong. For example, you are calling multiple checks to Fwd by doing:
if ((Fwd == true) && ... ) {
...
} else if ((Fwd == true) && ... ) {
...
} else if ((Fwd == true) && ... ) {
...
} else if ((Fwd == false) && ... ) {
...
} else if ((Fwd == false) && ... ) {
...
}
This uses up valuable resources in your program memory. It would be much more efficient to do a single check, and evaluate from there:
if (Fwd){
// Check sensor conditions here
} else {
// Check more sensor conditions here
}
In fact, you could probably omit the Fwd variable (unless you are using it elsewhere) altogether, saving you more memory space:
// Check whether to go forward or backwards.
// >= 50 - forward
// < 50 - backward
if (sensors[0] >= 50) {
// Check sensor conditions here
} else {
// Check more sensor conditions here
}
Overall, you could end up with something like:
// Check whether to go forward or backwards.
// >= 50 - forward
// < 50 - backward
if (sensors[0] >= 50) {
// Going forward, but which direction?
if (sensors[1] < 50) {
fwdRight();
} else if (sensors[2] < 50) {
fwdLeft();
} else {
// sensors[1] >= 50 AND sensors[2] >= 50
// Going straight forward
fwd();
}
} else {
// Check backward sensor conditions here
}
This answer might not directly answer your question, but it should help you diagnose better what is going on.

Converting if-else statement to if-else if-else statement

How do I convert this nested if-else statement into a non-nested if-else if-else statement? You may need to add some boolean operators to make this completely non-nested:
if (ball > 0) {
if (cup > 0) {
console.log(“I have a ball and cup.”);
} else {
console.log(“I have a ball.”);
}
} else {
if (cup > 0) {
console.log(“I have a cup”);
} else {
console.log(“I have nothing”);
}
}
If I understand what you are trying to do, then maybe this can help:
if (ball > 0 && cup > 0) {
console.log(“I have a ball and cup.”);
} else if (ball > 0) {
console.log(“I have a ball.”);
}
if (ball <= 0 && cup > 0) {
console.log(“I have a cup”);
} else if (ball <= 0) {
console.log(“I have nothing”);
}
Instead of nesting if-else statements, you can just check for multiple conditions in each if statement.

C++ if-else if Issues [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm having issues with my program below. It should convert numbers between 1-100 to AA,BA,BB,CB,CC,D,F. But it stops working and shows "BA" if I enter number less than 84. I checked the code. But I don't understand what is the problem.
#include <iostream>
using namespace std;
int main() {
int secenek,notu;
cout << "Not Dönüştürücü" << endl;
cout<<"Başlamak için 1'e basın:\n";
cin>>secenek;
if (secenek==1)
{
cout<<"Dönüştürülecek not: ";
cin>>notu;
}
if (notu<0 || notu>100)
{
cout<<"Geçerli bir not girin.\n";
}
else if (notu>=90)
{
cout<<"AA";
}
else if (notu<90 || notu>84)
{
cout<<"BA";
}
else if (notu<85 || notu>79)
{
cout<<"BB";
}
else if (notu<80 || notu>74)
{
cout<<"CB";
}
else if (notu<75 || notu>69)
{
cout<<"CC";
}
else if (notu<70 || notu>59)
{
cout<<"D";
}
else if (notu<60)
{
cout<<"F";
}
}
you made a logical error:
else if (notu<90 || notu>84)
should be
else if (notu<90 && notu>84)
and the same goes for all the following conditions.
EDIT as #Jarod42 suggested; you don't even need to check notu<90 anymore... your code could look like this:
if (notu<0 || notu>100)
{
cout<<"Geçerli bir not girin.\n";
}
else if (notu>=90)
{
cout<<"AA";
}
else if (notu>84)
{
cout<<"BA";
}
else if (notu>79)
{
cout<<"BB";
}
etc...
Your condition
else if (notu<90 || notu>84)
will always be true, whatever notu is set to. You probably mean
else if (notu < 90 && notu > 84)
The problematic part:
else if (notu<90 || notu>84)
{
cout<<"BA";
}
else if (notu<85 || notu>79)
{
cout<<"BB";
}
else if (notu<80 || notu>74)
{
cout<<"CB";
}
else if (notu<90 || notu> 84) will trigger on any notu lower than 90 and on any notu higher than 84. That's all pretty much all who survived the earlier check.
Correct implementation would be else if (notu<90 && notu> 84) which will only trigger if both conditions are met.
My C++ is a bit rusty, but if I remember correctly one could even write else if (84 < notu < 90).
EDIT: else if (84 < notu < 90) isn't valid C++ syntax.
The main problem is that you're using || where && would be logically correct.
But you don't really need && either - you can simplify a bit since in the else branch you already know that the corresponding if condition is false.
Like this:
if (notu < 0 || notu > 100)
{
cout << "Geçerli bir not girin.\n";
}
else if (notu >= 90)
{
cout << "AA";
}
else if (notu >= 85) // Already know that it's < 90, because it's not >= 90
{
cout << "BA";
}
// ...
// ...
else if (notu >= 60) // Already know that it's < 70
{
cout << "D";
}
else // Already know that it's < 60
{
cout << "F";
}