
why when i take out the else function it prints out 4 times? (The number is less than 5 -The number is greater than 5- The number is equal to 5 - The number is greater than 5
Resolved

Comments (3)
- Popular
- New
- Old
You must be signed in to leave a comment
Alan
27 October 2021, 11:55
ok thanks, Guadalup, i got it.
public class Solution {
public static void main(String[] args) {
compare(3);
compare(6);
compare(5);
}
public static void compare(int a) {
if(a==5){
System.out.println("The number is equal to 5");}
if (a<5){
System.out.println("The number is less than 5");}
else{
System.out.println("The number is greater than 5");}
}
}
thanks got it it was the else before the if statment i didnt understand
0
Guadalupe Gagnon
27 October 2021, 13:27
With if - else if - else statements they are linked together. The program will check each condition, 1 at a time, from top to bottom until the very first instance where the if condition is true. When it finds that first true it executes the code in the block for that if statement and then ignores the rest of the structure. If no statement is true then it will execute the block of code under the single else, which is the end of the structure. You can have as many if statements as you want in a structure but they must be linked together with the else keyword or they will be regarded as separate structures.
In the code you shared there are two 'if' structures:
So the logic will check if 'a' is equal to 5 at line 3 and output "The number is equal to 5" if true. Then at line 7 it checks if 'a' is less than 5 and outputs "The number is less than 5" if true, otherwise it outputs "The number is greater than 5".
Also,
just be aware that there are over 1300 tasks on this site and without specifics (the full code, the task conditions, the requirements that are not passing, etc) it makes it hard to provide help. There is a little slider bar on the page that you create a help post that allows you to share your current solution, with will have all of this information for us without you having to copy and paste. +2
Guadalupe Gagnon
24 October 2021, 04:08solution
how are we supposed to know what your code is doing when you only show half of it? It's asking a mechanic to diagnose why your lawn mower doesn't start and only giving them the carburetor from it.
Without seeing your code I can tell you that when the number 5 is passed to this method the code will output both:
The number is equal to 5
The number is greater than 5
+2