[Solved!] Problem with if statement returning else statement | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

[Solved!] Problem with if statement returning else statement

Iโ€™m writing this off of the if statement lesson for Java, and if you run it and put your age in as 14 or 15, it will return โ€œToo youngโ€ but also โ€œWelcome!โ€. How would I get it to not return Welcome on too young? https://code.sololearn.com/c8d1L51r9zk9/?ref=app

7th Nov 2018, 10:53 PM
p.xela
p.xela - avatar
4 Answers
+ 5
Its because both of your if which is <18 and ==18 are executed seperately First the code run in <18 it's true so "too young" appear Next the code run in ==18 its false because surely <18 is not same as 18, thats why welcome message appears use else if to connect both the if
7th Nov 2018, 11:10 PM
Taste
Taste - avatar
+ 3
Fixed! You were almost there ๐Ÿ˜ƒ Only thing you were missing was an โ€œelseโ€ before the second โ€œifโ€. Look: if (age < 18) { System.out.println("Too Young"); }else if (age == 18) { System.out.println("Just right"); }else { System.out.println("Welcome!"); } This solves yoir problem ๐Ÿ˜‡๐ŸŽน
7th Nov 2018, 11:10 PM
Carlos J. Rodriguez
Carlos J. Rodriguez - avatar
+ 2
Carlos J. Rodriguez that did it! thank you and thank you Taste ๐Ÿ‘
7th Nov 2018, 11:24 PM
p.xela
p.xela - avatar
0
000 is the anwser
12th Nov 2018, 3:47 PM
Henry Neal