2

I had a requirement that using the main method arguments we have to do operations like Sum,Subtraction,Multiplication... For example: If the input is java Compute 1 2 3 add the last argument should be taken as the input for Addition and do operation...

I have written follwing code for requirement but its is not going inside if condtion and execute the code..can any one help ... thanq


package com.project;

public class Compute 
{

public static void main(String[] args) 
{

    int Last = args.length-1;
    String method[] = {"add","sub","mul"};
    if(args[Last] == method[0])
    {
        //System.out.println(method[0]);
        int sum = 0;
        for(int i=0; i < args.length-1; i++)
        {
            sum += Integer.parseInt(args[i]);
            System.out.println("Sum is:"+sum);

        }
    }else if(args[Last] == method[1])
        {
            //System.out.println(method[0]);
            int sub = 0;
            for(int i=0; i < args.length-1; i++)
            {
                sub -= Integer.parseInt(args[i]);
                System.out.println("Substraction is:"+sub);
            }
        }else if(args[Last] == method[2])
            {
                //System.out.println(method[0]);
                int mul = 0;
                for(int i=0; i < args.length-1; i++)
                {
                    mul *= Integer.parseInt(args[i]);
                    System.out.println("Multiplication is:"+mul);
                }
    }
}
}
Anjali
  • 21
  • 2
  • 2
    Right from the start, I can tell you that you're going to need to use [proper string equality](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java). Something like this is where you can't use `==` and you have to use `.equals(Object)` – Obicere Sep 15 '17 at 16:57

1 Answers1

0

Use the .equals() method to compare String values. That should fix your problem.

The == operator checks if the references to the objects are equal.

Procrastinator
  • 2,526
  • 30
  • 27
  • 36
Fabri Pautasso
  • 485
  • 6
  • 17