在javaandroid中将字符串转换为int以查找结果

dfddblmv  于 2021-07-04  发布在  Java
关注(0)|答案(3)|浏览(487)

**结束。**此问题需要详细的调试信息。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

4个月前关门了。
改进这个问题
如何转换这样的字符 + , - , / , * ,来自 String 变成一个 int ,我尝试使用 int ,但是这个角色 + , - , / , * 当我试图从 String 进入 int ,
通常你打字的时候 int i = 12+12 它将显示 24 ,但当我试图把它从 Stringint ,我的应用程序强制关闭,有什么建议吗?谢谢

eqqqjvef

eqqqjvef1#

简单的方法应该是使用scriptengine库-
转到build.gradle(module:app). 添加此依赖项- implementation 'io.apisense:rhino-android:1.0' 然后要计算任何字符串的值,请执行以下操作-
对所有操作使用相同的代码( + - * \ % ),只需更改字符串值。

String s = "12+12";
    ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("rhino");
    try {
        Object result = scriptEngine.eval(s);
        System.out.println("Result: "+result); // Result(Output) is: 24
    } catch (ScriptException e) {
        e.printStackTrace();
    }

示例-用户在edittext中输入时 12+12 把它放进一个 String s = editText.getText().toString() 调用方法- String result = calculateResult(s); 方法是-

private String calculateResult(String s) {
        ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("rhino");
        Object result = null;
        try {
            result = scriptEngine.eval(s);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
        return result.toString();   // returns 24
    }
x4shl7ld

x4shl7ld2#

而不是 Integer.parseInt(getTextView); ,则必须首先从从 TextView 然后将它们分别转换成整数,再进行算术运算。
按以下步骤操作。

equal.setOnClickListener(new View.OnClickListener() {
    @Override             
    public void onClick(View v) {
        String getTextView = textView.getText().toString();
        String[] numbers = getTextView.split("+");
        int value = Integer.parseInt(numbers[0]) + Integer.parseInt(numbers[1]);
        textView.setText(value);  
    }
}

更新替换

String[] numbers = getTextView.split("+");

具有

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

以防止悬挂元字符错误。

yvgpqqbh

yvgpqqbh3#

按以下步骤操作:

// Split the string from textView on '+'. In order to specify optional space before/after '+', use \\s*
String[] nums = textView.getText().toString().split("\\s*\\+\\s*");

// Parse each number into an integer, add them and then set the result into textView
textView.setText(Integer.parseInt(nums[0]) + Integer.parseInt(nums[1]));

相关问题