我想创建一个运算符来划分问题 1:("+6x","2"), get("+3x");问题2:(“12”,“2”),得到(“6”)。

I want to create an operator to divide problem1:("+6x","2"), get("+3x"); problem2:("12","2"), get ("6").

我正在尝试在答案后面加x,方法我试过了,但是一个方法只能有一个return.

第一个if是去掉string中的x,除完之后,我想把它加回去

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);
}

这就是我想要的。

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));
}

但这是JUnit得到的,第一个条件得不到答案。我不知道如何在答案后添加 "x"。

    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));
}

我通过为结果添加另一个 if 语句解决了这个问题。代码是这样附上的。

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;


}