问题描述
如何将诸如+
,-
,/
,*
之类的字符从String
转换为int
,
我尝试使用int
找到一些结果,但是此字符+
,-
,/
,*
会导致错误,
当我尝试从String
转换为int
时,
通常,当您键入int i = 12+12
时,它将显示24
的结果,
但是当我尝试将其从String
转换为int
时,我的应用程序强制关闭,有任何建议吗?谢谢
解决方法
简单的方法应该使用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
}
,
您必须首先从从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("\\+");
防止悬空的元字符错误。
,执行以下操作:
// 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]));