2016-09-27 37 views
0

設計輸入字符串並輸出'true'或'false'的函數 - 告訴字符串是否是表達式。Java遞歸表達式檢查器

打印一條消息,告訴該字符串是否爲格式正確的表達式。最後,在處理完所有輸入後,程序打印出口消息並停止。 以下規則定義合式表達:

.expr> = S | I(C)T(.exp>) 

這是我的代碼:

import java.io.FileNotFoundException; 
import java.util.*; 
import java.util.Scanner; 

public class RecursionExpression { 


    public static void main(String[] args) throws FileNotFoundException{ 
     System.out.println("Enter the expression statement."); 
     Scanner keyboard = new Scanner(System.in); 
     String expr = keyboard.nextLine(); 
    } 
    public static boolean expression(String n) 
    { 
     if (n.charAt(0) == 's') 
     return true; 
     else if(n.length() >=6) 
     { 
      if (n.substring(0,5) == "I(C)T") 
       return expression(n.substring(6, n.length()-1)); 


     } 
     return false; 

    } 
} 
+0

基本上,你在這裏的下跌分配;並告訴我們你無法解決它。但你的問題是什麼?我們爲你做作業嗎?如果你不明白如何解釋expr的定義;你有沒有想過要求你的老師澄清? – GhostCat

+0

哎呀對不起,我沒有把正確的代碼。將立即更新。 –

回答

1

首先,所述第一字符是's'是不足的所有條件(以及根據所述規則它應該是大寫'S')。這甚至可以爲空字符串引發異常。此外,它接受任何字符串,以s開頭,包括"so you want this string to match too"

此外,您不檢查.exp>周圍的()括號,這也需要完成。此外比較String S中的不編譯與==時間常數不工作(見How do I compare strings in Java?):

public static boolean expression(String n) { 
    return n.equals("S") || 
      (n.startsWith("I(C)T(") && n.endsWith(")") && expression(n.substring(6, n.length()-1))); 
}