Question

In: Computer Science

You are given the main class RecursiveMethods.java which invokes methods that can be selected from a...

You are given the main class RecursiveMethods.java which invokes methods that can be selected from a menu. Your task is to implement two of these methods. -The first method isPal(s) determines whether a given string s is a palindrome. For example "12321" is a palindrome but "1231" is not. Currently the method isPal is a stub and you are expected to implement the method. -The second method isSAE(s) determines whether the given string s is a strict arithmetic expression (see below). This method is fully implemented for you. -The third method valueStrict(s) computes the value of the strict arithmetic expression s. Currently the method valueStrict is a stub and you are expected to implement the method using as a guide the implementation of isSAE(s). The methods should be implemented using recursive methods, no points will be given for iterative solutions. You should only need to work with the file RecursiveMethods.java but you will include your util1228 package for obvious reasons. Sample execution is shown below. SUBMISSION NOTES You will submit a single .jar file named A04.jar. Make sure that: 1) The jar file runs. In project properties under Run make sure the main class is set to a04.RecursiveMethods 2) The jar file includes all your source code. In project properties under packaging make sure .java files are not excluded. (see our Brightspace site for details about making JAR files) IMPORTANT NOTES A strict arithmetic expression (SAE) is one of the following: 1. Any nonnegative integer is a SAE (that is a nonempty string made of digits) 2. (x+y), (x*y), (-x), (+x), if x,y are SAEs Strict arithmetic expressions do not allow spaces and do not allow omitting parentheses. The following are valid SAEs: 12, (-12), (3*5), ((3*5)+10), ((-3)*((-5)+10)) The following are NOT valid SAEs: -12, 3*5, (-3)*5, (3), (5+4, (3 + 5) SAMPLE EXECUTION Menu 1. Test whether a given string is a palindrome 2. Test whether a given string is a strict arithmetic expression 3. Evaluate a strict arithmetic expression 4. Quit Enter your choice here: 1 Enter a string: 1234321 "1234321" is a palindrome Press enter to continue... Menu 1. Test whether a given string is a palindrome 2. Test whether a given string is a strict arithmetic expression 3. Evaluate a strict arithmetic expression 4. Quit Enter your choice here: 3 Enter a strict arithmetic expression: ((3*5)+10) The value is 25 Press enter to continue... Menu 1. Test whether a given string is a palindrome 2. Test whether a given string is a strict arithmetic expression 3. Evaluate a strict arithmetic expression 4. Quit Enter your choice here: 3 Enter a strict arithmetic expression: (-3)*5 ERROR: invalid arithmetic expression Press enter to continue... Menu 1. Test whether a given string is a palindrome 2. Test whether a given string is a strict arithmetic expression 3. Evaluate a strict arithmetic expression 4. Quit Enter your choice here: 4 Buy

ackage a04;

import java.util.Scanner;
import util1228.Menu;
import static util1228.Utilities.pause;
import static util1228.Utilities.isNumeric;

/**
 *
 * @author Joshua, Stavros
 */
public class RecursiveMethods {
    
    public static void main(String[] args) {
        Scanner kbd=new Scanner(System.in);
        Menu m=createMenu();
        int choice,n;
        String s;
        do{
            m.display();
            choice=m.getChoice();
            switch(choice){
                case 1:
                    System.out.print("Enter a string: ");
                    s=kbd.nextLine().trim();
                    System.out.println("\""+s+"\" is "
                        +((isPal(s.replace(" ", "").toLowerCase()))?"":"not ")
                        +"a palindrome");
                    pause();
                    break;
                case 2:
                    System.out.print("Enter a string: ");
                    s = kbd.nextLine().trim();
                    System.out.printf("The string is %sa valid strict arithmetic"
                                    + " expression\n", 
                                      (isSAE(s))?"":"*not* ");
                    pause();
                    break;
                case 3:
                    System.out.print("Enter a strict arithmetic expression: ");
                    s = kbd.nextLine().trim();
                    if (!isSAE(s)) {
                        System.out.println("ERROR: invalid arithmetic expression");
                        pause();
                        break;
                    }
                    System.out.printf("The value is %d\n", 
                                      valueStrict(s));
                    pause();
                    break;
                case 4:
                    System.out.println("\nBuy!\n");
                    break;
                case -1:
                    System.out.println("*** Invalid Choice");
                    pause();
                    break;
            }
        } while(choice!=4);
    }
    
    /**
     * This method creates the Menu for the program and adds each of the options
     *
     * @return the created Menu
     */
    private static Menu createMenu() {
        Menu m = new Menu("Menu", 8, 50);
        m.addOption("Test whether a given string is a palindrome");
        m.addOption("Test whether a given string is a strict arithmetic "
                + "expression");
        m.addOption("Evaluate a strict arithmetic expression");
        m.addOption("Quit");
        return m;
    }

    
    private static boolean isPal(String input) {
        System.out.println("***Method isPal is a stub. It always returns false."
                + "\n***You are expected to implement this method.");
        return false;
    }
    
    public static boolean isSAE(String s) {
        int l = s.length();
        if (l==0) return false;
        if (isNumeric(s)) return true;
        if (l<3) return false;
        if (s.charAt(0)!='(' || s.charAt(l-1)!=')')
            return false;
        //Here we know that s is of the form (...)
        String s1, s2;
        //Next test whether  s  is of the form  (+...) or (-...)
        if (s.charAt(1)=='+' || s.charAt(1)=='-') {
            s1 = s.substring(2,l-1);
            return isSAE(s1);
        }
        //Here we know that s is not of the form (+...) or (-...)
        //Next test whether  s is of the form (x+y) or (x*y); that is,
        //there is a position in s that contains  '+' or '*' and the 
        //parts of s to the left and right of '+' or '*' are SAEs
        for (int i=2; i<l-1; i++) {
            if (s.charAt(i)=='+' || s.charAt(i)=='*') {
                s1 = s.substring(1, i);
                s2 = s.substring(i+1,l-1);
                if (isSAE(s1) && isSAE(s2)) 
                    return true;
            }
        }
        return false;
    }

    
    public static int valueStrict(String s) {
        System.out.println("***Method valueStrict is a stub. It always returns "
                + "0.\n***You are expected to implement this method.");
        return 0;
    }

    
}

Solutions

Expert Solution

Hello, I have implemented both of the functions for you, I cannot test your program but I have tested the functions explicitly because in your program the Menu class was not given. If you have any further doubts you can always reach out to me in the comment section

/**
 *
 * @author Joshua, Stavros
 */
import java.util.*;

class RecursiveMethods {
    
    public static void main(String[] args) {
        Scanner kbd=new Scanner(System.in);
        Menu m=createMenu();
        int choice,n;
        String s;
        do{
            m.display();
            choice=m.getChoice();
            switch(choice){
                case 1:
                    System.out.print("Enter a string: ");
                    s=kbd.nextLine().trim();
                    System.out.println("\""+s+"\" is "
                        +((isPal(s.replace(" ", "").toLowerCase()))?"":"not ")
                        +"a palindrome");
                    pause();
                    break;
                case 2:
                    System.out.print("Enter a string: ");
                    s = kbd.nextLine().trim();
                    System.out.printf("The string is %sa valid strict arithmetic"
                                    + " expression\n", 
                                      (isSAE(s))?"":"*not* ");
                    pause();
                    break;
                case 3:
                    System.out.print("Enter a strict arithmetic expression: ");
                    s = kbd.nextLine().trim();
                    if (!isSAE(s)) {
                        System.out.println("ERROR: invalid arithmetic expression");
                        pause();
                        break;
                    }
                    System.out.printf("The value is %d\n", 
                                      valueStrict(s));
                    pause();
                    break;
                case 4:
                    System.out.println("\nBuy!\n");
                    break;
                case -1:
                    System.out.println("*** Invalid Choice");
                    pause();
                    break;
            }
        } while(choice!=4);
    }
    
    /**
     * This method creates the Menu for the program and adds each of the options
     *
     * @return the created Menu
     */
    private static Menu createMenu() {
        Menu m = new Menu("Menu", 8, 50);
        m.addOption("Test whether a given string is a palindrome");
        m.addOption("Test whether a given string is a strict arithmetic "
                + "expression");
        m.addOption("Evaluate a strict arithmetic expression");
        m.addOption("Quit");
        return m;
    }

    
    private static boolean isPal(String input) {
        System.out.println("***Method isPal is a stub. It always returns false."
                + "\n***You are expected to implement this method.");
        int n=input.length();
        if(n==0 || n==1) return true;
        if(input.charAt(0)==input.charAt(n-1)){
            return isPal(input.substring(1, n-1));
        }
        return false;
    }
    
    public static boolean isSAE(String s) {
        int l = s.length();
        if (l==0) return false;
        if (isNumeric(s)) return true;
        if (l<3) return false;
        if (s.charAt(0)!='(' || s.charAt(l-1)!=')')
            return false;
        //Here we know that s is of the form (...)
        String s1, s2;
        //Next test whether  s  is of the form  (+...) or (-...)
        if (s.charAt(1)=='+' || s.charAt(1)=='-') {
            s1 = s.substring(2,l-1);
            return isSAE(s1);
        }
        //Here we know that s is not of the form (+...) or (-...)
        //Next test whether  s is of the form (x+y) or (x*y); that is,
        //there is a position in s that contains  '+' or '*' and the 
        //parts of s to the left and right of '+' or '*' are SAEs
        for (int i=2; i<l-1; i++) {
            if (s.charAt(i)=='+' || s.charAt(i)=='*') {
                s1 = s.substring(1, i);
                s2 = s.substring(i+1,l-1);
                if (isSAE(s1) && isSAE(s2)) 
                    return true;
            }
        }
        return false;
    }

    
    public static int valueStrict(String s) {
        System.out.println("***Method valueStrict is a stub. It always returns "
                + "0.\n***You are expected to implement this method.");

        if (!s.contains("+") && !s.contains("-") && !s.contains("*") && !s.contains("/")) {
            return Integer.parseInt(s);
        }
    
        int i;
        for (i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == '+' || s.charAt(i) == '-') {
                break;
            } else if (s.charAt(i) == '*' || s.charAt(i) == '/') {
                break;
            }
        }
    
        String r1 = s.substring(0, i);
        String r2 = s.substring(i + 1, s.length());
    
        int result = 0;
    
        switch (s.charAt(i)) {
            case '+':
                result = valueStrict(r1) + valueStrict(r2);
                break;
            case '-':
                result = valueStrict(r1) - valueStrict(r2);
                break;
            case '*':
                result = valueStrict(r1) * valueStrict(r2);
                break;
            case '/':
                int right = valueStrict(r2);
                if (right == 0) //if denominator is zero
                {
                    System.out.println("Invalid divisor");
                    System.exit(1);
                } else {
                    result = valueStrict(r1) / right;
                }
                break;
        }
        return result;
    }

    
}


Related Solutions

package design; public class FortuneEmployee { /** * FortuneEmployee class has a main methods where you...
package design; public class FortuneEmployee { /** * FortuneEmployee class has a main methods where you will be able to create Object from * EmployeeInfo class to use fields and attributes.Demonstrate as many methods as possible * to use with proper business work flow.Think as a Software Architect, Product Designer and * as a Software Developer.(employee.info.system) package is given as an outline,you need to elaborate * more to design an application that will meet for fortune 500 Employee Information *...
When you create a C++ class, you are given 4 default methods. What are they and...
When you create a C++ class, you are given 4 default methods. What are they and why is it important that you remember that these exist?
You are given the following class definition (assume all methods are correctly implemented): public class Song...
You are given the following class definition (assume all methods are correctly implemented): public class Song { ... public Song(String name, String artist) { ... } public String getName() { ... } public String getArtist() { ... } public String getGenre() { ... } public int copiesSold() { ... } } Write NAMED and TYPED lambda expressions for each of the following, using appropriate functional interfaces from the java.util.function and java.util packages (Only the lambda expression with no type+name will...
You are given the following class definition (assume all methods are correctly implemented): public class Song...
You are given the following class definition (assume all methods are correctly implemented): public class Song { ... public Song(String name, String artist) { ... } public String getName() { ... } public String getArtist() { ... } public String getGenre() { ... } public int copiesSold() { ... } } Write NAMED and TYPED lambda expressions for each of the following, using appropriate functional interfaces from the java.util.function and java.util packages (Only the lambda expression with no type+name will...
**** IN C++ ***** 1.Given the class alpha and the main function, modify the class alpha...
**** IN C++ ***** 1.Given the class alpha and the main function, modify the class alpha so the main function is working properly. #include <iostream> using namespace std; //////////////////////////////////////////////////////////////// class alpha { private: int data; public: //YOUR CODE }; //////////////////////////////////////////////////////////////// int main() { alpha a1(37); alpha a2; a2 = a1; cout << "\na2="; a2.display(); //display a2 alpha a3(a1); //invoke copy constructor cout << "\na3="; a3.display(); //display a3 alpha a4 = a1; cout << "\na4="; a4.display(); cout << endl; return 0;...
Given: You are given a Python Class template. In this class there is a class variable...
Given: You are given a Python Class template. In this class there is a class variable vector, is a list of N non-negative integers and are stored (in positions 0, 1, 2, ... (N-1)), where at least one integer is 0. Task: Write a recursive function "findAllPaths" to find all possible path through V starting at position 0, and ending at the location of 0, in accordance with the Rule below. If no such path exists, "paths" should be an...
How to print these methods in a separate main class? need the output to look like...
How to print these methods in a separate main class? need the output to look like this: Enter three integers whose GCD is to be found -> Enter an integer n to find the nth Fibonacci number -> Enter the base and exponent , an integer, of a power -> Enter two positive integers 1 and j where i < j -> gcd() = fib() = (a number ^ a number) = a number There are ___ palindromic numbers between...
In this lab you will learn how to use methods from the Math class in order...
In this lab you will learn how to use methods from the Math class in order to calculate the area or the volume of several different shapes. If you are confused about the Methods you can access from the Math class and would like to see some examples click here. Hint: Most of these methods can be done in one line. Step 1 - circleArea In this method you will calculate the area of a circle. Before you can calculate...
Given the main method of a driver class, write a Fraction class. Include the following instance...
Given the main method of a driver class, write a Fraction class. Include the following instance methods: add, multiply, print, printAsDouble, and a separate accessor method for each instance variable. Write a Fraction class that implements these methods: add ─ This method receives a Fraction parameter and adds the parameter fraction to the calling object fraction. multiply ─ This method receives a Fraction parameter and multiplies the parameter fraction by the calling object fraction. print ─ This method prints the...
You are given a string literal “CS3360” Describe what is Stringbuilder class, 3 member methods in...
You are given a string literal “CS3360” Describe what is Stringbuilder class, 3 member methods in Stringbuilder class and use the above literal to show output of 3 methods.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT