1

I am trying to add x after the answer, I have tried the way, but one method can only have one return.

the first if is to remove the x from string, after the divide, I want to add it back.

public String apply(Vector args) 
{
    //define two string variables
    String expString1 = (String)args.get(0);
    String expString2 = (String)args.get(1);
    String s = "";
    //move the x if the last char is x.
     if (expString1.charAt(expString1.length()-1) == 'x'){s = expString1.substring(1, expString1.length()-1);
     }else if (expString1.charAt(expString1.length()-1) != 'x') {s = expString1;}
     //convert string to int, and do the divide operator.
     int n2 = Integer.parseInt(expString2);
     int n1 = Integer.parseInt(s);
     int result = n1 / n2;
    //get result, but not the one I want, especially for x string. 
    return String.valueOf(result);
}

this is what I want get.

public void testApplyVector() {
    Vector arg = new Vector();
    arg.add("+6x");
    arg.add("2");
    Divide add = new Divide();
    assertEquals("+3x", add.apply(arg));

    Vector arg2 = new Vector();
    arg2.add("12");
    arg2.add("2");
    assertEquals("6", add.apply(arg2));
}

but this is the JUnit get, the first condition can't get the answer. I don't how to add a "x" after the answer.

    public void testApplyVector() {
    Vector arg = new Vector();
    arg.add("+6x");
    arg.add("2");
    Divide add = new Divide();
    assertEquals("3", add.apply(arg));

    Vector arg2 = new Vector();
    arg2.add("12");
    arg2.add("2");
    assertEquals("6", add.apply(arg2));
}
Qing Li
  • 21
  • 1
  • 5
  • I think its not working because `expString1.substring(1, expString1.length()-1` is wrong, change that to `expString1.substring(0, expString1.length()-1`. You want the substring from the first element. – TheChetan Dec 02 '17 at 17:58
  • Yes, that's true. But this can't solve the problem, I still can't get "+3x". I removed it before the divide, but how can I add "x" back? – Qing Li Dec 02 '17 at 23:08

1 Answers1

0

I solved the problem by adding another if statement for the result. Code is attached like this.

public String apply(Vector args) 
{
    //define two string variables
    String expString1 = (String)args.get(0);
    String expString2 = (String)args.get(1);
    String s = "";

    //move the x if the last char is x.
     if (expString1.charAt(expString1.length()-1) == 'x'){
         s = expString1.substring(0, expString1.length()-1);
     }else if (expString1.charAt(expString1.length()-1) != 'x') {
         s = expString1;}
     //convert string to int, and do the divide operator.
     int n2 = Integer.parseInt(expString2);
     int n1 = Integer.parseInt(s);
     int div = n1 / n2;
     //this is what i add, to check is the expString1 has a x.
     String result = String.valueOf(div);
     if (expString1.contains("x")) { return result = result + "x"; }
     else  return result;


}
Qing Li
  • 21
  • 1
  • 5