+ 2

why i m not getting the output. I would appreciate any help.

import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner a = new Scanner(System.in); String method = a.nextLine(); if(method=="a"){ a(); } else if(method=="b"){ b(); } } public static void a(){ System.out.println("a"); } public static void b(){ System.out.println("b"); } }

11th Mar 2017, 4:42 PM
shobhit
shobhit - avatar
3 odpowiedzi
+ 6
Heres the error, replace method=="a" and method == "b" with method.equals("a") and method.equals("b") That will work, Also there is a LOT of different between .equals and ==
11th Mar 2017, 4:55 PM
Meharban Singh
Meharban Singh - avatar
+ 2
@Vishal Prajapati else if is proper syntax @shobhit .equals compares the value stored in an object unless you override the method and write your own implementation == compares the reference of an object but it works fine on primitives
11th Mar 2017, 11:42 PM
Earl Chukwu
Earl Chukwu - avatar
- 1
here comes the error. else if. you should correct. } else { if(method=="b"){ b(); } Hope it works
11th Mar 2017, 4:45 PM
Vishal Prajapati