在java中在字符串中添加数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19301991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:50:56  来源:igfitidea点击:

Adding numbers within a string in java

javastringparsingint

提问by metelofe

How do I add two numbers within one string?

如何在一个字符串中添加两个数字?

I have:

我有:

String a = "(x+x)";
String lb = "2";

String b = a.replace("x", lb);

int c = ?

it outputs 2+2, how do I get it to add them together correctly into an integer?

它输出2+2,我如何让它正确地将它们加在一起成一个整数?

采纳答案by sushain97

While you can use a Java library to achieve this goal as mentioned in the comments, there issomething built into Java since version 6 which may be useful (but maybe a little overkill). I suggest this not because I believe it's particularly efficient but rather as an alternative to using a library.

虽然你可以使用Java库,以实现在评论中提到这个目标,还有因为6版本,这可能是有用的(但也许有点矫枉过正)内置到Java的东西。我建议这样做不是因为我认为它特别有效,而是作为使用库的替代方法。

Use JavaScript:

使用 JavaScript:

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

ScriptEngine jsRuntime = new ScriptEngineManager().getEngineByName("javascript");
String expression = "2+2"; //The expression you would to evaluate.
double result = (Double) jsRuntime.eval(expression);

回答by rgettman

Use the Integer.parseIntmethodto parse a Stringinto an int, then add the values. Adding strings just concatenates them.

使用该Integer.parseInt方法将 a 解析String为 an int,然后添加值。添加字符串只是将它们连接起来。

回答by DT7

You can use parseInt()method.

您可以使用parseInt()方法。

回答by Dónal

It seems your question could be summarised as

看来你的问题可以概括为

How do I convert a String such as "2+2"to the number 4

如何将字符串转换为"2+2"数字4

Here's a solution that uses only the standard Java libraries:

这是一个仅使用标准 Java 库的解决方案:

    String sumExpression = "2+2";
    String[] numbers = sumExpression.split("\+");

    int total = 0;

    for (String number: numbers) {
        total += Integer.parseInt(number.trim());
    }

    // check our result
    assert total == 4;