Я бы порекомендовал использовать регулярные выражения и их "групповую" функциональность.Я бы на самом деле удалил все пробелы, чтобы сделать вещи проще, вычеркнул бы это из уравнения, еще одну вещь, с которой нужно иметь дело.И, очевидно, я бы порекомендовал упростить строку, заменив "-" на "+", "* +" на "*" и т. Д.
теперь вы можете использовать регулярное выражение в вашей очищенной строке.
Pattern firstPat = Pattern.compile("(((\\+|-)?)\\d+(.\\d+)?)");//for matching the first number, leading sign is optional
Pattern remainingPat = Pattern.compile("(\\+|-)(\\d+(.\\d+)?)");//for remaining numbers, leading sign is mandatory.
Pattern remainingPatWithExtOps = Pattern.compile("(\\*|/|\\+|-)(-?\\d+(.\\d+)?)");//for remaining numbers, accommodating multiply and divide with negative signs(positive signs should have been cleaned out)
Matcher match = firstPat.matcher(inputString);
теперь вы можете перебирать строку, используя метод match.find()
.а затем используйте match.group(1)
, чтобы получить знак / операцию, и используйте match.group(2)
, чтобы получить число ...
Итак ...
Double firstnum;
boolean firstNumSigned = false;
if(match.find())
{
firstNum = Double.parse(match.group(0));// Parsing handles possible sign in string.
//obv check for exceptions during this and double check group num
String tmp = match.group(1);
firstNumSigned = tmp.equals("+") || tmp.equals("-");
}
else
{//no match means the input was probably invalid....
throw new IllegalArgumentException("What the heck were you thinking inputting that?!");
}
match = remainingPat.matcher(inputString);//use our other pattern for remaining numbers
if(firstNumSigned)
{
match.find();//a signed first number will cause success here, we need to ignore this since we already got the first number
}
Double tmpRemaingingNum;
String operation;
while(match.find())
{
operation = match.group(1);
tmpRemainingNum = Double.parse(match.group(2));
//Do what you want with these values now until match.find() returns false and you are done
}
PS: код не проверенЯ довольно уверен в регулярном выражении, но я не уверен на 100% насчет группирующих скобок на первом шаблоне .. возможно, придется поэкспериментировать