我正在 GUI 上开发我的第一个计算器项目,我获取输入并使用 Action Listner 将其连接到字符串字段中。
calculation = calculation + " 4 ";
calculation = calculation + " * ";
calculation = calculation + " 9 ";
使用子字符串取出第一个数字和第二个数字,将它们转换并放入两个字段中
num1 = Integer.parseInt(calculation.substring(0, 1));
num2 = Integer.parseInt(calculation.substring(4, 5));
问题是我不能在运算符之前使用超过 x 位数字、在运算符之后使用超过 y 位数字的子字符串。 我可以使用 subString 内置方法来做到这一点吗?如果我不能,我怎样才能使用其他方法来做到这一点?
最佳答案
您可以使用String.split
和String.contains
:
String equation = "4+ 10";
equation.replaceAll(" ", "");//get rid if the space
String[] buffer = null;
if (equation.contains("+"))
buffer = equation.split("\\+");
else if (equation.contains("*"))
buffer = equation.split("\\*");
else if (equation.contains("/"))
buffer = equation.split("\\/");
else if (equation.contains("-"))
buffer = equation.split("\\-");
if(buffer != null && buffer.length == 2)
{
int term1 = Integer.parseInt(buffer[0]);
int term2 = Integer.parseInt(buffer[1]);
//call you calculation ode
}else
System.out.println("Fail to parse equation");
或者按照 Vince Emigh 的建议使用单个正则表达式:
String equation = "4+ 10";
equation.replaceAll(" ", "");//get rid if the space
final String [] buffer = equation.split("\\+|\\*|\\-|\\/");
if(buffer.length == 2)
{
int term1 = Integer.parseInt(buffer[0]);
int term2 = Integer.parseInt(buffer[1]);
//call you calculation ode
}else
System.out.println("Fail to parse equation");
关于java - 是否可以在运算符之前和之后剪切字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26658861/