Note that there are some explanatory texts on larger screens.

plurals
  1. POJava IndexOutOfBoundsException Error
    primarykey
    data
    text
    <p>I realize that this may be and is probably a really dumb question but bare with me, I'm a newbie. Anyway, 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.</p> <pre><code>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 &lt;= 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); } } } </code></pre> <p>The string array parsedOperands looks like this: [null, +, -, *, /]. The string array parsedIntegers looks like this: [3, 9, 2, 10, 5].</p> <p>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?</p> <p>Here is the error:</p> <pre><code>[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 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload