1

I am trying to solve https://www.codechef.com/problems/FLOW010 problem. I wrote `

public static void main (String[] args) throws java.lang.Exception
    {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        while(t>0){
            String s=sc.next();
            if(s=="b" || s=="B"){
                System.out.println("BattleShip");
            }
            else if(s=="c" || s=="C"){
                System.out.println("Cruiser");
            }
            else if(s=="d" || s=="D"){
                System.out.println("Destroyer");
            }
            else if(s=="f" || s=="F"){
                System.out.println("Frigate");
            }
            t--;
        }
    }

` There is no mistake in terms of syntax. Please help me what is mistake

Sachin
  • 55
  • 1
  • 5

1 Answers1

1

Replace all your == comparisons for String like this:

String s=sc.next();
if(s.equalsIgnoreCase("b") {
    System.out.println("BattleShip");
}
// ... etc.
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • 1
    Thank you! can you explain why not to use == ? What is problem in it? – Sachin Apr 25 '20 at 08:50
  • 1
    @Sachin `==` is used to check the reference or memory address of the objects to check whether they point to the same location or not. Since `String` is non-primitive `equals()` method is used to compare the contents of the `String`. So in your case you are trying to match `String s` have the desired character (b or B in your case). So to check that you have to use the `equals()` method. You can refer for more [here](https://www.java67.com/2012/11/difference-between-operator-and-equals-method-in.html) – Hasitha Jayawardana Apr 25 '20 at 09:06