我正在创建一个具有附加功能的java Web服务。我想把1 + 1的总和作为'2',而不是得到'11'。我该怎么做才能解决这个错误?
以下是我的代码:
Addition.java
public class Addition {
private String firstNumber, secondNumber, sum;
public Addition(String firstNumber, String secondNumber, String sum) {
this.firstNumber = firstNumber;
this.secondNumber = secondNumber;
this.sum = firstNumber+secondNumber;
}
public String getFirstNumber() {
return firstNumber;
}
public void setFirstNumber(String first) {
this.firstNumber = first;
}
public String getSecondNumber() {
return secondNumber;
}
public void setSecondNumber(String second) {
this.secondNumber = second;
}
public String getSum() {
return sum;
}
public void setSum(String sum) {
this.sum = sum;
}
@Override
public String toString() {
return "Addition [firstNumber=" + firstNumber + ", secondNumber=" +
secondNumber + ", sum=" + sum + "]";
}
AdditionController.java
@RestController
public class AdditionController {
private static final String template = " %s";
@RequestMapping("/addition")
@ResponseBody
public Addition addition (
@RequestParam(value="firstNumber", defaultValue="1") String firstNumber,
@RequestParam(value="secondNumber", defaultValue="1") String secondNumber,
@RequestParam(value="sum", defaultValue="2") String sum){
return new Addition(
String.format(template, firstNumber),
String.format(template, secondNumber),
String.format(template, sum));
}
}
我无法将'string'更改为'int',因为如果我尝试这样做,我会遇到更多错误。有人请帮帮我。非常感谢你。
答案 0 :(得分:1)
如果您不想更改任何定义,那么只是为了解决方法,请尝试仅更改此行:
this.sum = firstNumber+secondNumber;
到
this.sum = String.valueOf(Integer.parseInt(firstNumber.trim())+Integer.parseInt(secondNumber.trim()));
不要忘记处理异常。
N.B。: 这不是正确的方法。只是努力工作。
答案 1 :(得分:1)
正如其他人已经在评论中指出的那样,如果您要总结int
个值,则必须解析 String
(s)到int
( s)某处;你可以在构造函数中这样做。我在下面提供了一个几乎可以替代的替代品 - 然而,我认为将sum
传递给班级(或者提供一个直接的变异器以获得总和)是没有意义的;相反,我会重新计算第一个或第二个数字的更新。像,
public class Addition {
private int firstNumber, secondNumber, sum;
public Addition(String firstNumber, String secondNumber) {
this.firstNumber = Integer.parseInt(firstNumber.trim());
this.secondNumber = Integer.parseInt(secondNumber.trim());
updateSum();
}
public int getFirstNumber() {
return firstNumber;
}
public void setFirstNumber(int firstNumber) {
this.firstNumber = firstNumber;
updateSum();
}
public int getSecondNumber() {
return secondNumber;
}
public void setSecondNumber(int secondNumber) {
this.secondNumber = secondNumber;
updateSum();
}
public int getSum() {
return sum;
}
private void updateSum() {
this.sum = this.firstNumber + this.secondNumber;
}
@Override
public String toString() {
return String.format("Addition [firstNumber=%d, secondNumber=%d, sum=%d%n", //
firstNumber, secondNumber, sum);
}
}