Common mistakes made when using if, else if, else statements - Java programming tutorial beginner
Coding River
Common mistakes made when using if, else if, else statements
In this video, We will talk about some of the common errors made by new programmers in regards to if, else if, else statements or selection control structures
The first error is: Not putting the parenthesis around the logical expression Consider this portion of code that I have written here
If condition System.out.println(“You are eligible to vote”);
If you run this portion of code, you will get a syntax error and the reason is that the logical expression must always be surrounded by parentheses So when using if statements in your program, you always have to keep that in mind
The second most common error is: Putting a semi-colon right after the condition statement, in a one-way selection control structure
Consider this portion of code If (condition); System.out.println(“You are eligible to vote”);
This code will lead to a semantic mistake Meaning that the program will run, but it will return an unexpected result Because the if statement will operate on an empty statement That is to say that the if statement will consider that there is no statement to execute even if the condition is met
The third common mistake is: putting a semicolon after the right parenthesis and before the first statement, in a two-way selection statement
Consider this portion of code
If (condition); System.out.println(“You are eligible to vote”); else System.out.println(“You are not eligible to vote”);
This portion of code will lead to a syntax error. If the if statement ends with a semicolon, That means that the first statement is no longer part of the if statement And the else part of the if...else statement will stand by itself. In Java, we cannot have a stand-alone else statement; That is to say that, the else statement cannot be separated from the if statement. So, that is the reason why we are getting a syntax error.
The fourth common mistake is: not using curly braces when you have more than one action statement to execute
Consider the following portion of code if (condition) System.out.println(“You are eligible to vote”); System.out.println(“You are no longer a minor”);
The portion of code will definitely lead to a semantic error The program will run, but the result will be very confusing
You might probably think that both output statements are the action statements of the if statement But, in reality that ‘s not the case Because these output statements are not contained in curly braces, the if statement will act on only one output statement which is the first one As for the second output statement, it will still execute whether the condition evaluates to true or false This is confusing
In order to correct that, we have to use the curly braces to form compound st ... https://www.youtube.com/watch?v=x30MJfPm3Us
14800631 Bytes