我想创建一个运算符来分割problem1 :(“+ 6x”,“2”),get(“+ 3x”); problem2 :(“12”,“2”),get(“6”)。

我想在答案后加上x,我试过了,但是一种方法只能有一个返回。我想创建一个运算符来分割problem1 :(“+ 6x”,“2”),get(“+ 3x”); problem2 :(“12”,“2”),get(“6”)。

第一个如果是从字符串中去掉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;

}

以上是 我想创建一个运算符来分割problem1 :(“+ 6x”,“2”),get(“+ 3x”); problem2 :(“12”,“2”),get(“6”)。 的全部内容, 来源链接: utcz.com/qa/257554.html

回到顶部