我正在研究GUI上的第一个Calculator项目,我获取输入并使用Action Listner在String字段中将其连接。
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内置方法吗?如果我不能,我怎么能通过使用任何其他方法来做到这一点?
答案 0 :(得分:1)
您可以使用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");