2012-02-26 10 views
0

こんにちは私は私の論理式を格納した文字のarraylistを持っています。私のコードはリスト内の変数を数え、私の問題は同じ変数を持つが、記号と括弧があるときです。例えば:xy + zy '変数の数は4でなければならず、yとy'は異なる。文字のArraylistでの変数の決定Java

public void simplify(String strexp){ 

int length = strexp.length(); 

    //get the size and variables used in expression 
    List<Character> usedVariables = new ArrayList<Character>(); 
    for (int i = 0; i < length; i++) { 
     char c = strexp.charAt(i); 
     if (Character.isLetter(c) && !usedVariables.contains(c)&&usedVariables.contains('\'')) { 
      usedVariables.add(c); 
     } 
    } 
} 

答えて

1

変数が1文字よりも長い場合は、文字列ではなく文字列の配列リストを考慮する必要があります。

1

はたぶん、あなたは使用してコードを再設計したい本:

Matcher m = Pattern.compile("[a-z]'?").matcher(strExpr); 
while (m.find()) { 
    String var = m.group(); 
    ... 
} 
+0

方法私の式は括弧を持っている場合はどうですか? –

+0

残念ながら、あなたがしたいことは私には全く分かりません。単純な構文解析/解釈では '('を押して ')'を押してスタックを使うことができます。 –

+0

私は真理値表を作るつもりで、最初にその式で使われる変数を特定する必要があります。真理値表の2つの出力は、単純化されていない式と簡略化された式に由来します。 –

0

これはあなたの問題への単純な可能な解決策

public static void simplify(String strexp){ 

     int length = strexp.length(); 

      //get the size and variables used in expression 
      java.util.List<String> usedVariables = new ArrayList<String>(); 
      for (int i = 0; i < length; i++) { 
       String c = strexp.charAt(i) + "";  

        // check for character which are not actual 


       if (!usedVariables.contains(c)) { 
        usedVariables.add(c); 
       }else{ 
        if((i+1) < length){ 
         String c2 = strexp.charAt(i+1) + ""; 

         if(c2.equals("'")){ 
          c = c + c2; 
          if (!usedVariables.contains(c)) { 
           usedVariables.add(c); 
          } 
         } 
        }     
       } 
      } 
      System.out.println(""+usedVariables.size()); 
     } 
関連する問題