0

This Java program is successfully compiled and run and accepting input from the user but for every city value(Meerut, Noida, Agra), it is showing "Unknown City" Why?? Why it is always executing else condition?? I have used both sc.next() and sc.nextLine(), but in both cases i am getting the same output.

import java.util.Scanner;
public class JTP_If_Else_If_Ladder{
    public static void main(String args[]){
        //String city="";
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter City Name\t:\t");
        //String city=sc.next();
        String city=sc.nextLine();
        System.out.println("You Entered\t:\t"+city);
        if(city=="Meerut"){
            System.out.println("City is Meerut.");
        }
        else if(city=="Noida"){
            System.out.println("City is Noida.");
        }
        else if(city=="Agra"){
            System.out.println("City is Agra.");
        }
        else{
            System.out.println("Unknown City");  
            /* for city=Meerut,Noida,Agra; why this "else block" always execute */
        }
        sc.close();
    }
}
  • 2
    besides how to compare Strings, I assume you understand that System.out.println("City is " + city); is a whole lot less code to write? – Stultuske Sep 17 '21 at 06:34
  • You might also benefit from trimming your input (e.g. trailing spaces) & accepting lower-case input, too? – m.reiter Sep 17 '21 at 06:56

0 Answers0