Search code examples
javabooleanboolean-expressionboolean-operations

Boolean Expression AND Gate Java


Hi I have a code that when you input an expression it will store to an array but my problem is how can i put * between two variables when the input expression is like ab +c?it says null value. here's my code:

 stack = strexp.toCharArray();       
 for (int k = 0; k < stack.length; k++) {
   if (Character.isLetter(stack[k]) && Character.isLetter(stack[k+1])){
     temp[k] = stack[k];
     temp[k+1] = '*';
     temp[k+2] = stack[k+1];
   }
 }

Solution

  • You should receive an ArrayIndexOutOfBounds exception, because you increment k until it is equal to the last index in the stack array and then you try to access stack[k+1].

    Your loop expression has to be

    for (int k = 0; k < (stack.length-1); k++)
    

    The cause of the NullPointerException is not directly visible but I believe that you haven't initialized the temp array. Most likely because you do not know it's exact size.

    I'd store the result in a list StringBuilder instead:

    StringBuilder resultBuilder = new StringBuilder();
    for (int k = 0; k < (stack.length-1); k++) {
       resultBuilder.append(stack[k]);
       if (Character.isLetter(stack[k]) && Character.isLetter(stack[k+1])) {
         resultBuilder.append('*');
      }
    }
    resultBuilder.append(stack[stack.length-1]);  // don't forget the last element