Question

Could somebody please help.!

Please DON't copy paste from other places and please read the question and answer exactly what's asked.

Thank you I much appreciate it.

You are to write a program name MyArrayStack.java that create/build the ArrayStack data structure. The class must be written

Note: 1: In public static void main(String[] args), you need to ask user to enter the string s first, then call the Testl(s)

0 0
Add a comment Improve this question Transcribed image text
Answer #1


// MyArrayStack.java

public class MyArrayStack {
  
   private Object arr[];
   private int top;
  
   // default constructor
   public MyArrayStack()
   {
       arr = new Object[10];
       top = -1;
   }
  
   // parameterized constructor
   public MyArrayStack(int n)
   {
       arr = new Object[n];
       top = -1;
   }
  
   // method to push an object at top of stack
   public boolean push(Object x)
   {
       if(top < (arr.length-1))
       {
           top++;
           arr[top] = x;
           return true;
       }
      
       return false;
   }
  
   //method to remove and return the element at top of stack
   public Object pop()
   {
       if(!isEmpty())
       {
           Object obj = arr[top];
           top--;
           return obj;
       }
      
       return null;
   }
  
   // method to return the top element of stack
   public Object peek()
   {
       if(!isEmpty())
       {
           return arr[top];
       }
      
       return null;
   }
  
   // method to return true of stack is empty , else false
   public boolean isEmpty()
   {
       return(top == -1);
   }  
}

//end of MyArrayStack.java

// TestStack.java

import java.util.Scanner;

public class TestStack {
  
   // method to return true if S belongs to the given language else false
   public boolean TestL(String S)
   {
       // create an array of size of the length of the String S
       MyArrayStack stack = new MyArrayStack(S.length());
       int i=0;
       // loop over the string until "$" is encountered, pushing the characters into the stack
       while((i < S.length()) && (S.charAt(i) != '$'))
       {
           stack.push(new Character(S.charAt(i)));
           i++;
       }
      
       i++; // ignore $
      
       // loop over the remaining string, comparing the characters of the string with the character in the stack
       while( i < S.length())
       {
           // if stack is empty, then return false
           if(stack.isEmpty())
               return false;
           else if(!stack.peek().equals(new Character(S.charAt(i)))) // if current character of the string doesn't match the character at top of stack, return false
               return false;
           stack.pop(); // if characters match, remove the character from stack and analyse the next character in the string
           i++;
       }
      
       // after analysing all the characters in the string, if stack is not empty, return false
       if(!stack.isEmpty())
           return false;
      
       return true; // S belongs to the language
   }

   public static void main(String[] args)
   {
       String S;
       Scanner scan = new Scanner(System.in);
       // input of string
       System.out.print("Enter an input string: ");
       S = scan.nextLine();
       TestStack ts = new TestStack(); // create an object of TestStack
// test if S is in language or not
       if(ts.TestL(S))
           System.out.println(S+" is in the given language");
       else
           System.out.println(S+" is not in the given language");
       scan.close();
   }
}

//end of TestStack.java

Output:

Enter an input string: madam$madam madam$madam is in the given language

Enter an input string: race$eca race$eca is not in the given language

Add a comment
Know the answer?
Add Answer to:
Could somebody please help.! Please DON't copy paste from other places and please read the question...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Need Help ASAP!! Below is my code and i am getting error in (public interface stack)...

    Need Help ASAP!! Below is my code and i am getting error in (public interface stack) and in StackImplementation class. Please help me fix it. Please provide a solution so i can fix the error. thank you.... package mazeGame; import java.io.*; import java.util.*; public class mazeGame {    static String[][]maze;    public static void main(String[] args)    {    maze=new String[30][30];    maze=fillArray("mazefile.txt");    }    public static String[][]fillArray(String file)    {    maze = new String[30][30];       try{...

  • I need to implement a stack array but the top of the stack has to be...

    I need to implement a stack array but the top of the stack has to be Initialize as the index of the last location in the array.    //Array implementation of stacks.    import java.util.Arrays;       public class ArrayStack implements Stack {        //Declare a class constant called DEFAULT_STACK_SIZE with the value 10.           private static final int DEFAULT_STACK_SIZE = 10;           /* Declare two instance variables:            1. An integer called...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

  • Hello. I need help writing the following Java Program. Thank you Develop a class encapsulating the...

    Hello. I need help writing the following Java Program. Thank you Develop a class encapsulating the concept of a college course, assuming that a course has following attributers: code (for instance COSC1337), a description, and a number of credits (for instance 3). Include a constructor, the accessors, mutators and methods ‘toString’, ‘equals’, and ‘finalize’. Write a client class to test the behavior of the class and its methods. The outline of the class is given as follows: public class Course...

  • PLEASE WRITE IN JAVA AND ADD COMMENTS TO EXPLAIN write a class NameCard.java which has •Data...

    PLEASE WRITE IN JAVA AND ADD COMMENTS TO EXPLAIN write a class NameCard.java which has •Data fields: name (String), age(int), company(String) •Methods: •Public String getName(); •Public int getAge(); •Public String getCom(); •Public void setName(String n); •Public void setAge(int a); •Public void setCom(String c); •toString(): \\ can be used to output information on this name card 2, write a class DoublyNameCardList.java, which is a doubly linked list and each node of the list a name card. In the DoublyNameCardList.java: •Data field:...

  • *JAVA* Can somebody take a look at my current challenge? I need to throw a different...

    *JAVA* Can somebody take a look at my current challenge? I need to throw a different exception when a)(b is entered. It should throw "Correct number of parenthesis but incorrect syntax" The code is as follows. Stack class: public class ArrayStack<E> {    private int top, size;    private E arrS[];    private static final int MAX_STACK_SIZE = 10;    public ArrayStack() {        this.arrS = (E[]) new Object[MAX_STACK_SIZE];        this.top = size;        this.size = 0;...

  • the answer must be in java. thank you Question 2 [8 points] Consider the class Class...

    the answer must be in java. thank you Question 2 [8 points] Consider the class Class A below: class Class A implements Serializable{ int a; static int b; transient int c; String s; // Constructor public Class A (int a, int b, int c, Strings){ this.a = a; this.b = b; this.c = c; this.s = s; Complete the class Test to test the serialization and deserialization of the objects of class Class A. State the possible variable values following...

  • Java Program 1. Write a class that reads in a group of test scores (positive integers...

    Java Program 1. Write a class that reads in a group of test scores (positive integers from 1 to 100) from the keyboard. The main method of the class calls a few other methods to calculate the average of all the scores as well as the highest and lowest score. The number of scores is undetermined but there will be no more than 50. A negative value is used to end the input loop. import java.util.Scanner; public class GradeStat {...

  • Analyze the following code: public class Test { public int x; public Test(String t) { System.out.println("Test");...

    Analyze the following code: public class Test { public int x; public Test(String t) { System.out.println("Test"); public static void main(String[] args) { Test test: System.out.println(test.x); The program has a compile error because Test class does not have a default constructor The program has a compile error because test is not initialized OO The program has a compile error because x has not been initialized The program has a runtime NullPointerException while executing test.x because test is a null reference and...

  • Using your Dog class from earlier this week, complete the following: Create a new class called...

    Using your Dog class from earlier this week, complete the following: Create a new class called DogKennel with the following: Instance field(s) - array of Dogs + any others you may want Contructor - default (no parameters) - will make a DogKennel with no dogs in it Methods: public void addDog(Dog d) - which adds a dog to the array public int currentNumDogs() - returns number of dogs currently in kennel public double averageAge() - which returns the average age...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT