Infix to Postfix ' StringIndexOutOfBoundsException' error [duplicate]What is IndexOutOfBoundsException? How can I fix it?infix to postfixInfix to Postfix using stacks and Precedence of OperatorsUnderstanding Postfix-expression Evaluation in Java code using a stackInfix to Postfix using stackconvert infix to postfixHow do I properly test whether my postfix expression is valid?Infix calculatorCreating a postfix converterDoes pushing a character onto a stack change the string it comes from?Infix to Postfix program doesn't work as intended

Why is oil used as as the lubricant in power generators, while water is the most available, cheapest and accessible lubricant?

Ethics: Is it ethical for a professor to conduct research using a student's ideas without giving them credit?

How would you idiomatically translate the French saying "Il n’y a pas d'amour, il n’y a que des preuves d’amour" to English?

Relationship between two graph optimization problems

Is there such a thing as Intrusive-L (as opposed to Intrusive-R)?

CEO says not to expect pay increases unless you do something really exceptional. Is this counter-productive?

Is there a preferred time in their presidency when US presidents pardon the most people?

I noticed an error in a graded exam during office hours. Should I give the student the lower grade?

Patent Agreement in Order to Graduate

How to remove solidified paste from toothbrush

SSD not reaching advertised speed

Why would one use "enter the name of the project to confirm"?

Was Haile Selassie the world's only involuntary messiah?

If a photon truly goes through both slits (at the same time), then why can't we detect it at both slits (at the same time)?

Should I present forged documents in a Penetration Test/Red team engagement?

How do you get the Super Rod in Pokémon Sword and Shield?

Consequences of eigenvector-eigenvalue formula found by studying neutrinos

Are conjugate vectors unique?

Using a sealant to stop a toilet tank leak

Mistake with Whole/Half step intervals problem

Locked folder with obscure app from Sourceforge, now cannot unlock folder

"Indexed" version of compactness and Axiom of Choice

What does "lequel" mean in this sentence, and how does the rest of its grammar operate?

A new type of builder pattern



Infix to Postfix ' StringIndexOutOfBoundsException' error [duplicate]


What is IndexOutOfBoundsException? How can I fix it?infix to postfixInfix to Postfix using stacks and Precedence of OperatorsUnderstanding Postfix-expression Evaluation in Java code using a stackInfix to Postfix using stackconvert infix to postfixHow do I properly test whether my postfix expression is valid?Infix calculatorCreating a postfix converterDoes pushing a character onto a stack change the string it comes from?Infix to Postfix program doesn't work as intended






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









0



















This question already has an answer here:



  • What is IndexOutOfBoundsException? How can I fix it? [duplicate]

    1 answer



I am setting up a method that turn a infix string into a postfix equation with a custom LinkStack.



I have tried to to check if the charAt(i) was null and a if statement to check if i is greater than exp.length() but neither worked.



public static String infixToPostfix(String exp) 

// make variable
String result = new String("");
int temp = 0;
LinkedStack stack = new LinkedStack();

for (int i = 0; i<exp.length(); ++i)

char c = exp.charAt(i);
if(Character.isDigit(c))

int n = 0;

//extract the characters and store it in num
while(Character.isDigit(c))

n = n*10 + (int)(c-'0');
i++;
c = exp.charAt(i); //exception occurs
System.out.println(n);

i--;

//push the number in stack
stack.push(n);
//System.out.println(stack.size() + ", Stack size");


// If ( push it to the stack.
if (c == '(')
stack.push(c);

// If ) pop and output from the stack
// until an '(' is encountered.
else if (c == ')')

while (!stack.isEmpty() && stack.peek() != '(')
result += stack.pop();

if (!stack.isEmpty() && stack.peek() != '(')
return "Invalid Expression"; // invalid expression
else
stack.pop();

else // an operator is encountered

while (!stack.isEmpty() && pre(c) <= pre((char) stack.peek()))
result += stack.pop();
stack.push(c);




// pop all the operators from the stack
while (!stack.isEmpty())
result += stack.pop();

String temp2 = stack.print();
System.out.println(temp2);
return result;



I expect the output to be 469 645 + if the input is 496+645 but the actual output is java.lang.StringIndexOutOfBoundsException: String index out of range: 7.










share|improve this question















marked as duplicate by Nathan Hughes java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
Mar 29 at 17:31


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

























    0



















    This question already has an answer here:



    • What is IndexOutOfBoundsException? How can I fix it? [duplicate]

      1 answer



    I am setting up a method that turn a infix string into a postfix equation with a custom LinkStack.



    I have tried to to check if the charAt(i) was null and a if statement to check if i is greater than exp.length() but neither worked.



    public static String infixToPostfix(String exp) 

    // make variable
    String result = new String("");
    int temp = 0;
    LinkedStack stack = new LinkedStack();

    for (int i = 0; i<exp.length(); ++i)

    char c = exp.charAt(i);
    if(Character.isDigit(c))

    int n = 0;

    //extract the characters and store it in num
    while(Character.isDigit(c))

    n = n*10 + (int)(c-'0');
    i++;
    c = exp.charAt(i); //exception occurs
    System.out.println(n);

    i--;

    //push the number in stack
    stack.push(n);
    //System.out.println(stack.size() + ", Stack size");


    // If ( push it to the stack.
    if (c == '(')
    stack.push(c);

    // If ) pop and output from the stack
    // until an '(' is encountered.
    else if (c == ')')

    while (!stack.isEmpty() && stack.peek() != '(')
    result += stack.pop();

    if (!stack.isEmpty() && stack.peek() != '(')
    return "Invalid Expression"; // invalid expression
    else
    stack.pop();

    else // an operator is encountered

    while (!stack.isEmpty() && pre(c) <= pre((char) stack.peek()))
    result += stack.pop();
    stack.push(c);




    // pop all the operators from the stack
    while (!stack.isEmpty())
    result += stack.pop();

    String temp2 = stack.print();
    System.out.println(temp2);
    return result;



    I expect the output to be 469 645 + if the input is 496+645 but the actual output is java.lang.StringIndexOutOfBoundsException: String index out of range: 7.










    share|improve this question















    marked as duplicate by Nathan Hughes java
    Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

    StackExchange.ready(function()
    if (StackExchange.options.isMobile) return;

    $('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
    var $hover = $(this).addClass('hover-bound'),
    $msg = $hover.siblings('.dupe-hammer-message');

    $hover.hover(
    function()
    $hover.showInfoMessage('',
    messageElement: $msg.clone().show(),
    transient: false,
    position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
    dismissable: false,
    relativeToBody: true
    );
    ,
    function()
    StackExchange.helpers.removeMessages();

    );
    );
    );
    Mar 29 at 17:31


    This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





















      0













      0









      0









      This question already has an answer here:



      • What is IndexOutOfBoundsException? How can I fix it? [duplicate]

        1 answer



      I am setting up a method that turn a infix string into a postfix equation with a custom LinkStack.



      I have tried to to check if the charAt(i) was null and a if statement to check if i is greater than exp.length() but neither worked.



      public static String infixToPostfix(String exp) 

      // make variable
      String result = new String("");
      int temp = 0;
      LinkedStack stack = new LinkedStack();

      for (int i = 0; i<exp.length(); ++i)

      char c = exp.charAt(i);
      if(Character.isDigit(c))

      int n = 0;

      //extract the characters and store it in num
      while(Character.isDigit(c))

      n = n*10 + (int)(c-'0');
      i++;
      c = exp.charAt(i); //exception occurs
      System.out.println(n);

      i--;

      //push the number in stack
      stack.push(n);
      //System.out.println(stack.size() + ", Stack size");


      // If ( push it to the stack.
      if (c == '(')
      stack.push(c);

      // If ) pop and output from the stack
      // until an '(' is encountered.
      else if (c == ')')

      while (!stack.isEmpty() && stack.peek() != '(')
      result += stack.pop();

      if (!stack.isEmpty() && stack.peek() != '(')
      return "Invalid Expression"; // invalid expression
      else
      stack.pop();

      else // an operator is encountered

      while (!stack.isEmpty() && pre(c) <= pre((char) stack.peek()))
      result += stack.pop();
      stack.push(c);




      // pop all the operators from the stack
      while (!stack.isEmpty())
      result += stack.pop();

      String temp2 = stack.print();
      System.out.println(temp2);
      return result;



      I expect the output to be 469 645 + if the input is 496+645 but the actual output is java.lang.StringIndexOutOfBoundsException: String index out of range: 7.










      share|improve this question















      This question already has an answer here:



      • What is IndexOutOfBoundsException? How can I fix it? [duplicate]

        1 answer



      I am setting up a method that turn a infix string into a postfix equation with a custom LinkStack.



      I have tried to to check if the charAt(i) was null and a if statement to check if i is greater than exp.length() but neither worked.



      public static String infixToPostfix(String exp) 

      // make variable
      String result = new String("");
      int temp = 0;
      LinkedStack stack = new LinkedStack();

      for (int i = 0; i<exp.length(); ++i)

      char c = exp.charAt(i);
      if(Character.isDigit(c))

      int n = 0;

      //extract the characters and store it in num
      while(Character.isDigit(c))

      n = n*10 + (int)(c-'0');
      i++;
      c = exp.charAt(i); //exception occurs
      System.out.println(n);

      i--;

      //push the number in stack
      stack.push(n);
      //System.out.println(stack.size() + ", Stack size");


      // If ( push it to the stack.
      if (c == '(')
      stack.push(c);

      // If ) pop and output from the stack
      // until an '(' is encountered.
      else if (c == ')')

      while (!stack.isEmpty() && stack.peek() != '(')
      result += stack.pop();

      if (!stack.isEmpty() && stack.peek() != '(')
      return "Invalid Expression"; // invalid expression
      else
      stack.pop();

      else // an operator is encountered

      while (!stack.isEmpty() && pre(c) <= pre((char) stack.peek()))
      result += stack.pop();
      stack.push(c);




      // pop all the operators from the stack
      while (!stack.isEmpty())
      result += stack.pop();

      String temp2 = stack.print();
      System.out.println(temp2);
      return result;



      I expect the output to be 469 645 + if the input is 496+645 but the actual output is java.lang.StringIndexOutOfBoundsException: String index out of range: 7.





      This question already has an answer here:



      • What is IndexOutOfBoundsException? How can I fix it? [duplicate]

        1 answer







      java indexoutofboundsexception postfix-notation infix-notation






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 28 at 22:08









      L0cusL0cus

      14 bronze badges




      14 bronze badges





      marked as duplicate by Nathan Hughes java
      Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

      StackExchange.ready(function()
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function()
      $hover.showInfoMessage('',
      messageElement: $msg.clone().show(),
      transient: false,
      position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
      dismissable: false,
      relativeToBody: true
      );
      ,
      function()
      StackExchange.helpers.removeMessages();

      );
      );
      );
      Mar 29 at 17:31


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.











      marked as duplicate by Nathan Hughes java
      Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

      StackExchange.ready(function()
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function()
      $hover.showInfoMessage('',
      messageElement: $msg.clone().show(),
      transient: false,
      position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
      dismissable: false,
      relativeToBody: true
      );
      ,
      function()
      StackExchange.helpers.removeMessages();

      );
      );
      );
      Mar 29 at 17:31


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









      marked as duplicate by Nathan Hughes java
      Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

      StackExchange.ready(function()
      if (StackExchange.options.isMobile) return;

      $('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
      var $hover = $(this).addClass('hover-bound'),
      $msg = $hover.siblings('.dupe-hammer-message');

      $hover.hover(
      function()
      $hover.showInfoMessage('',
      messageElement: $msg.clone().show(),
      transient: false,
      position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
      dismissable: false,
      relativeToBody: true
      );
      ,
      function()
      StackExchange.helpers.removeMessages();

      );
      );
      );
      Mar 29 at 17:31


      This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
























          1 Answer
          1






          active

          oldest

          votes


















          0



















           while(Character.isDigit(c)) 

          n = n*10 + (int)(c-'0');
          i++;
          c = exp.charAt(i); //exception occurs
          System.out.println(n);



          You aren't length checking here, so you readily parse right off the end of the string.



           while(i < exp.length() && Character.isDigit(c)) 

          n = n*10 + (int)(c-'0');
          if (++i < exp.length())
          c = exp.charAt(i); //exception occurs

          System.out.println(n);



          Note: I'd cache the length because of how many times you use it, but that's not the cause of your problem.



          Note, however, that this is cleaner code style:



          public class Foo 
          public static void main(String[] args)
          String myString = "12345";
          int index = 0;
          for (char c: myString.toCharArray())
          System.out.printf("Char at %d == %cn", index, c);
          ++index;





          Notice the for-loop. I didn't do your calculations or break out or anything, but this is a cleaner way.



          You can also do...



          for (int index = 0; index < exp.length(); ++index) 
          char c = exp.charAt(index);
          if (!Character.isDigit(c))
          break;

          // Do other stuff here.



          There are a variety of other ways to structure your code. Your while loop is awkward.






          share|improve this answer




























          • That edit still gives me the same error.

            – L0cus
            Mar 28 at 22:21











          • Hmm. You're right. I've edited my answer.

            – Joseph Larson
            Mar 29 at 16:24











          • The shape of your code is a little odd. You can do a for-loop instead. I'll edit my answer once more.

            – Joseph Larson
            Mar 29 at 16:30


















          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0



















           while(Character.isDigit(c)) 

          n = n*10 + (int)(c-'0');
          i++;
          c = exp.charAt(i); //exception occurs
          System.out.println(n);



          You aren't length checking here, so you readily parse right off the end of the string.



           while(i < exp.length() && Character.isDigit(c)) 

          n = n*10 + (int)(c-'0');
          if (++i < exp.length())
          c = exp.charAt(i); //exception occurs

          System.out.println(n);



          Note: I'd cache the length because of how many times you use it, but that's not the cause of your problem.



          Note, however, that this is cleaner code style:



          public class Foo 
          public static void main(String[] args)
          String myString = "12345";
          int index = 0;
          for (char c: myString.toCharArray())
          System.out.printf("Char at %d == %cn", index, c);
          ++index;





          Notice the for-loop. I didn't do your calculations or break out or anything, but this is a cleaner way.



          You can also do...



          for (int index = 0; index < exp.length(); ++index) 
          char c = exp.charAt(index);
          if (!Character.isDigit(c))
          break;

          // Do other stuff here.



          There are a variety of other ways to structure your code. Your while loop is awkward.






          share|improve this answer




























          • That edit still gives me the same error.

            – L0cus
            Mar 28 at 22:21











          • Hmm. You're right. I've edited my answer.

            – Joseph Larson
            Mar 29 at 16:24











          • The shape of your code is a little odd. You can do a for-loop instead. I'll edit my answer once more.

            – Joseph Larson
            Mar 29 at 16:30















          0



















           while(Character.isDigit(c)) 

          n = n*10 + (int)(c-'0');
          i++;
          c = exp.charAt(i); //exception occurs
          System.out.println(n);



          You aren't length checking here, so you readily parse right off the end of the string.



           while(i < exp.length() && Character.isDigit(c)) 

          n = n*10 + (int)(c-'0');
          if (++i < exp.length())
          c = exp.charAt(i); //exception occurs

          System.out.println(n);



          Note: I'd cache the length because of how many times you use it, but that's not the cause of your problem.



          Note, however, that this is cleaner code style:



          public class Foo 
          public static void main(String[] args)
          String myString = "12345";
          int index = 0;
          for (char c: myString.toCharArray())
          System.out.printf("Char at %d == %cn", index, c);
          ++index;





          Notice the for-loop. I didn't do your calculations or break out or anything, but this is a cleaner way.



          You can also do...



          for (int index = 0; index < exp.length(); ++index) 
          char c = exp.charAt(index);
          if (!Character.isDigit(c))
          break;

          // Do other stuff here.



          There are a variety of other ways to structure your code. Your while loop is awkward.






          share|improve this answer




























          • That edit still gives me the same error.

            – L0cus
            Mar 28 at 22:21











          • Hmm. You're right. I've edited my answer.

            – Joseph Larson
            Mar 29 at 16:24











          • The shape of your code is a little odd. You can do a for-loop instead. I'll edit my answer once more.

            – Joseph Larson
            Mar 29 at 16:30













          0















          0











          0









           while(Character.isDigit(c)) 

          n = n*10 + (int)(c-'0');
          i++;
          c = exp.charAt(i); //exception occurs
          System.out.println(n);



          You aren't length checking here, so you readily parse right off the end of the string.



           while(i < exp.length() && Character.isDigit(c)) 

          n = n*10 + (int)(c-'0');
          if (++i < exp.length())
          c = exp.charAt(i); //exception occurs

          System.out.println(n);



          Note: I'd cache the length because of how many times you use it, but that's not the cause of your problem.



          Note, however, that this is cleaner code style:



          public class Foo 
          public static void main(String[] args)
          String myString = "12345";
          int index = 0;
          for (char c: myString.toCharArray())
          System.out.printf("Char at %d == %cn", index, c);
          ++index;





          Notice the for-loop. I didn't do your calculations or break out or anything, but this is a cleaner way.



          You can also do...



          for (int index = 0; index < exp.length(); ++index) 
          char c = exp.charAt(index);
          if (!Character.isDigit(c))
          break;

          // Do other stuff here.



          There are a variety of other ways to structure your code. Your while loop is awkward.






          share|improve this answer
















           while(Character.isDigit(c)) 

          n = n*10 + (int)(c-'0');
          i++;
          c = exp.charAt(i); //exception occurs
          System.out.println(n);



          You aren't length checking here, so you readily parse right off the end of the string.



           while(i < exp.length() && Character.isDigit(c)) 

          n = n*10 + (int)(c-'0');
          if (++i < exp.length())
          c = exp.charAt(i); //exception occurs

          System.out.println(n);



          Note: I'd cache the length because of how many times you use it, but that's not the cause of your problem.



          Note, however, that this is cleaner code style:



          public class Foo 
          public static void main(String[] args)
          String myString = "12345";
          int index = 0;
          for (char c: myString.toCharArray())
          System.out.printf("Char at %d == %cn", index, c);
          ++index;





          Notice the for-loop. I didn't do your calculations or break out or anything, but this is a cleaner way.



          You can also do...



          for (int index = 0; index < exp.length(); ++index) 
          char c = exp.charAt(index);
          if (!Character.isDigit(c))
          break;

          // Do other stuff here.



          There are a variety of other ways to structure your code. Your while loop is awkward.







          share|improve this answer















          share|improve this answer




          share|improve this answer








          edited Mar 29 at 16:32

























          answered Mar 28 at 22:19









          Joseph LarsonJoseph Larson

          1,8901 gold badge12 silver badges15 bronze badges




          1,8901 gold badge12 silver badges15 bronze badges















          • That edit still gives me the same error.

            – L0cus
            Mar 28 at 22:21











          • Hmm. You're right. I've edited my answer.

            – Joseph Larson
            Mar 29 at 16:24











          • The shape of your code is a little odd. You can do a for-loop instead. I'll edit my answer once more.

            – Joseph Larson
            Mar 29 at 16:30

















          • That edit still gives me the same error.

            – L0cus
            Mar 28 at 22:21











          • Hmm. You're right. I've edited my answer.

            – Joseph Larson
            Mar 29 at 16:24











          • The shape of your code is a little odd. You can do a for-loop instead. I'll edit my answer once more.

            – Joseph Larson
            Mar 29 at 16:30
















          That edit still gives me the same error.

          – L0cus
          Mar 28 at 22:21





          That edit still gives me the same error.

          – L0cus
          Mar 28 at 22:21













          Hmm. You're right. I've edited my answer.

          – Joseph Larson
          Mar 29 at 16:24





          Hmm. You're right. I've edited my answer.

          – Joseph Larson
          Mar 29 at 16:24













          The shape of your code is a little odd. You can do a for-loop instead. I'll edit my answer once more.

          – Joseph Larson
          Mar 29 at 16:30





          The shape of your code is a little odd. You can do a for-loop instead. I'll edit my answer once more.

          – Joseph Larson
          Mar 29 at 16:30





          Popular posts from this blog

          How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

          Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?