import java.util.Scanner; /** Accept.java - Let's use recursion to determine whether a given string * satisfies a certain property. For example, let's consider the language * (i.e. set of strings) a^n b^n. In other words, strings of the form * aaaaaaa...bbbbbbb... where the number of a's and b's are the same. */ public class Accept { public static void main(String [] args) { Scanner kbd = new Scanner(System.in); System.out.printf("Please enter a string: "); String s = kbd.nextLine(); if (isGood(s)) System.out.printf("It is a member of the language a^n b^n.\n"); else System.out.printf("No, not a member of a^n b^n.\n"); } public static boolean isGood(String s) { // Happy base case: the empty string works. if (s.equals("")) return true; // The length of the string must be even. If odd, reject. else if (s.length() % 2 == 1) return false; // Next, verify that the first character is 'a' and last char is 'b'. // If not, reject. char c1 = s.charAt(0); char c2 = s.charAt(s.length() - 1); if (! (c1 == 'a' && c2 == 'b')) return false; // Here is the recursive case: remove outermost characters. else return isGood(s.substring(1, s.length() - 1)); } }