1

I'm trying to do CNF operator in Java and I have an error with equality.

Firstly, I did most of the software but I didn't do totally.

My codes are here :

import acm.program.*;
public class split extends ConsoleProgram{
public void run()
{
    String veri     = "(p or q or s or t or k) and (p or q)";
    String yeni     = tekrarsil(parcala(veri));

    int []sayilar = new int[yeni.length()];
    for (int i = 0; i < yeni.length(); i++) {
        sayilar[i] = readInt("give a number for "+yeni.charAt(i)+" :");

    }
    for (int i = 0; i < sayilar.length; i++) {
        println(sayilar[i]);
    }
}

public String parcala(String veri)
{
    String yenistr  = "";
    String yeni[]   = veri.split("and");
    for (int j = 0; j < yeni.length; j++) {
        String yveri[] = yeni[j].split("or");
        for (int i = 0; i < yveri.length; i++) {
            yveri[i] = yveri[i].trim();
            if(i==0){
                yenistr = yenistr.concat(yveri[i].substring(1));

            }else if(i==yveri.length-1){
                yenistr = yenistr.concat(yveri[i].substring(0,yveri[i].length()-1));

            }else{
                yenistr = yenistr.concat(yveri[i]);

            }
        }
    }
    return (yenistr);
}
public String tekrarsil(String S)
{
        for (int i = 0; i < S.length(); i++)
            for (int k = i+1; k <= S.length()-1; k++){
                if (S.charAt(i) == S.charAt(k))
                {
                    S = S.substring(0,k)+ S.substring(k+1,S.length());
                    k--;
                }
            }
        return S;

     }
    }

The problem is the equality.

The program should check the variables is true or false.

For instance :

(p or q or s or t or k) and (q or p)

this program does like bellow:

give a number for p : 1(user will give a number one (true) or zero(false))
give a number for q : 0
give a number for s : 1
give a number for t : 0
give a number for k : 0
(if the variable use more than one, program will ask once)

If we look at these variables, we can see that (1 or 0 or 1 or 0 or 0) and (1 or 0) It will return true but I can't do this. I can't understand how to do it.

Best wishes.

4

1 回答 1

2

这个解决方案进行一些修改以适应您当前的需求怎么样?

或者,作为一种粗略的解决方法,您可以将Rhino用作 JavaScript 引擎,只需将操作的文本表示更改为运算符,如&&||等,然后让 JS 引擎评估并为您提供结果。

如果您只对表达式的输出值感兴趣,那么以上内容就足够了。

如果您需要设计自己的算法,那么您需要自己编写一个解析器,这是一项繁琐但可行的工作。

让用户与运算符一起输入所有表达式(从实现的角度来看,这不会有太大的不同)。您当然需要验证输入。您需要处理的数据是0, 1,括号(触发结果堆叠/取消堆叠)和运算符本身(另外,还有空格,但您应该简单地忽略它们)。

基本上,从左到右进行评估,您获取第一个数据参数(或者0, 1)并将其放入当前结果中。然后您读取运算符并将其应用于结果和下一条数据。依此类推,直到您到达输入的末尾。遇到括号时,最简单的做法是让解析器使用括号内的表达式递归调用自身(您应该匹配它们)并将返回值视为序数数据。

于 2013-05-11T22:05:04.010 回答