Don't know why my if...else statements in Java only print the else statements | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Don't know why my if...else statements in Java only print the else statements

Hello guys, I wrote two Java codes that use a scanner to take in a string (using the .nextLine method). One code has an if & an else statement The other one has if, else if & else statements but both codes will only execute the else commands and I don't know why. Whether I enter the strings (to execute the if or the else if statements with " " or without " ", still only the else statements get executed. Can anyone figure out why? I will copy both codes below and then a link to each. First, here is the first code: import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String password = scanner.nextLine(); if (password == "Jam") { System.out.println("You may enter"); } else { System.out.println("Access denied!"); } } } Second, here is the second code: import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String sport = scanner.nextLine; if (sport == "basketball") { System.out.println("You will practice " + sport + " in the Michael Jordan gym."); } else if (sport == "volleyball") { System.out.println("You will practice in the Misty May-Treanor gym."); } else { System.out.println("Please enter a sport"); } } } And the links are: https://code.sololearn.com/c74pKOOQOpJK https://code.sololearn.com/cEECH91SLi7E Thank you in advance for your help! Iulia

26th Aug 2022, 2:05 AM
Iulia
2 Answers
+ 3
The equals() method compares two strings, and returns true if the strings are equal, and false if not. if (password.equals("Jam")) { if (sport.equals("basketball")) {
26th Aug 2022, 2:15 AM
SoloProg
SoloProg - avatar
+ 1
Oh my God it Works!! Thank you, Thank you Thankyou!
26th Aug 2022, 2:31 AM
Iulia