mardi 19 janvier 2021

Compare user input to a string in java [duplicate]

I want to make a simple console calculator in Java and I want to ask the user that which operation do you want to perform here is my code to get a better understanding.

import java.util.*;
public class Calculator
{
    public static Integer add(Integer numb1 ,Integer numb2) 
    {
        Integer result = numb1 + numb2;
        return result;
    }
    public static void main(String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Which Operation do you want to perform : ");
        String operate = sc.next();
        if(operate == "add")
        {
            System.out.print("Enter 1st no.");
            Integer fnumb = sc.nextInt();
            System.out.print("Enter 2nd no.");
            Integer snumb = sc.nextInt();
            result = add(fnumb, snumb);
            System.out.println(result);
        }
        sc.close();
    }   
}

I think the code is right but the lines under the if condition never executes please help.

And please don't write that you don't need to use if-else because you only have 1 method that is - add() because I will add more methods like subtract and multiply

Aucun commentaire:

Enregistrer un commentaire