I'm trying to read a math expression like 3+9-2*10/5 from JOptionPane and get its result -- taking into account order of operations, of course. I split up the string into just digits and just operands using String.split() and created a for loop that is looking for either multiplication signs or division signs -- in this case it is detecting the string "*" since it comes up first in the string.
public static void main(String[] args)
{
String mathString = JOptionPane.showInputDialog("Please type a simple math expression (i.e., without parentheses).");
String[] parsedIntegers = mathString.split("\\D");
String[] parsedOperands = mathString.split("\\d+");
parsedOperands[0] = null;
System.out.println(Arrays.toString(parsedIntegers));
System.out.println(Arrays.toString(parsedOperands));
for (int index = 1; index <= parsedOperands.length; index = index + 1)
{
if (parsedOperands[index].equals("*"))
{
System.out.println("The multiplication sign is at index " + index + ".");
int multResult = Character.getNumericValue(parsedIntegers[index - 1].charAt(index - 1)) * Character.getNumericValue(parsedIntegers[index].charAt(index));
System.out.println(multResult);
}
}
}
The string array parsedOperands looks like this: [null, +, -, *, /]. The string array parsedIntegers looks like this: [3, 9, 2, 10, 5].
However, when I look for "*" which is at index 3 in parsedOperands and then try to multiply what is in (index - 1) and (index) in parsedIntegers, Java returns an IndexOutOfBoundsException. Why does this happen? Am I missing something?
Here is the error:
[3, 9, 2, 10, 5]
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
[null, +, -, *, /]
The multiplication sign is at index 3.
at java.lang.String.charAt(String.java:658)
at programmingpractice.SolveMathExpression.main(SolveMathExpression.java:49)
Java Result: 1
Each element in your array parsedIntegers
is a single-character string, so when you use charAt
, it should just be charAt(0)
:
int multResult = Character.getNumericValue(parsedIntegers[index - 1].charAt(0)) *
Character.getNumericValue(parsedIntegers[index].charAt(0));
Using charAt(index)
or charAt(index - 1)
there tries to read past the end of the one-character string and throws the StringIndexOutOfBoundsException
you got.
However, a more robust way to do this is probably to use Integer.parseInt
so you can have multi-digit integers:
int multResult = Integer.parseInt(parsedIntegers[index - 1]) *
Integer.parseInt(parsedIntegers[index]);