0

Design the function to input a string and output 'true' or 'false' - telling whether or not the string is an expression.

Print a message telling whether the string is a well-formed expression. Finally, after processing all the input, the program prints an exit message and stops. The following rule defines a well-formed expression:

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

Here is my code:

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;

    }
}
fabian
  • 80,457
  • 12
  • 86
  • 114
  • Basically you dropped your assignment here; and telling us that you cant solve it. But what is your question? That we do your homework for you? If you don't understand how to interpret that expr definition; did you consider asking your teacher for clarification? – GhostCat Sep 27 '16 at 08:05
  • Whoops sorry i did not put in the right code. Will update right now. – Joel starry Sep 27 '16 at 08:13

1 Answers1

1

First of all the condition that the first character is 's' is insufficient (and according to the rule it should be an uppercase 'S' BTW). This can even throw an exception for empty strings. Furthermore it accepts any string starting with an s, including "so you want this string to match too".

Furthermore you do not check for the () brackets around .exp>, which also needs to be done. Furthermore comparing Strings that are not compile time constants with == does not work (see 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)));
}
Community
  • 1
  • 1
fabian
  • 80,457
  • 12
  • 86
  • 114