布尔表达式AND Gate Java

时间:2012-02-12 18:07:24

标签: java boolean boolean-expression boolean-operations

您好我有一个代码,当您输入一个表达式时,它将存储到数组但我的问题是当输入表达式像ab + c时,我如何将*放在两个变量之间?它表示空值。 这是我的代码:

 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];
   }
 }

2 个答案:

答案 0 :(得分:2)

您应该收到ArrayIndexOutOfBounds例外,因为您将k增加到等于stack数组中的最后一个索引,然后然后访问stack[k+1]

你的循环表达式必须是

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

NullPointerException的原因不是直接可见,但我相信您尚未初始化temp数组。很可能是因为你不知道它的大小。

我将结果存储在列表 StringBuilder中:

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

答案 1 :(得分:0)

有两个问题:

1)NPE - 将通过初始化temp[]

来解决

2)Character.isLetter(stack[k + 1])

处的ArrayIndexOutOfBoundsException

使用此代码解决这两个问题:

    String strexp = "ab+c";
    char[] stack = strexp.toCharArray();
    for (int k = 0; k < stack.length - 1; k++)
    {
        if (Character.isLetter(stack[k]) && Character.isLetter(stack[k + 1]))
        {
            char temp[] = new char[3];
            temp[k] = stack[k];
            temp[k + 1] = '*';
            temp[k + 2] = stack[k + 1];
        }
    }