Question

Please just fill in the codes where this CharacterOrganizer.java class asks for (Bolded). It's a simple...

Please just fill in the codes where this CharacterOrganizer.java class asks for (Bolded). It's a simple Java Stacks assignment. I'll rate you thumbs up! Thank you

Program Info: Your program needs to read in characters and push them into the stack called startStack. Then your program should remove each element from the startStack from its top one by one, and the objective to insert all characters into the stack called finalStack in the alphabetical order. If the top character of the startStack is 'a', then you can push 'a' into the finalStack. However, if it is some other larger character, then it needs to wait to be pushed into the finalStack until all characters that are smaller than it are already pushed into the finalStack.
Here, we will be using other stacks called supportingStacks. The number of such supporting stacks will be specified by a user as well and it will be an array of Stack objects.

Copyable Content of CharacterOrganizer.java:

import java.util.Stack;

public class CharacterOrganizer
 {
  private Stack<Character> startStack; //stack contains characters in an order specified by a user
  private Stack<Character> finalStack; //stack to have characters in sorted order after running this algorithm
  private Stack<Character>[] supportingStacks; //stacks to hold some characters that are not in either start or final stack
  private int sizeOfStartStack; //the start stack size
  private int numberOfSupportingStacks; //number of supporting stacks, specified by a user
  private char smallestCharacter; //current smallest character that can be moved to the final stack
  private int stackWithNextSmallest; //the index of supporting stack that contains the next smallest character
  private final int ASCII_FOR_a = ((int) 'a'); //ASCII number for a, we can use it to keep track of smallest/largest characters


  //Constructor to initialize member variables
  public CharacterOrganizer(int sizeOfStartStack, int numOfSupportingStacks)
    {
          startStack = new Stack<Character>();
          finalStack = new Stack<Character>();
      this.sizeOfStartStack = sizeOfStartStack;
      this.numberOfSupportingStacks = numOfSupportingStacks;

      supportingStacks = new Stack[numberOfSupportingStacks];

      for (int i=0; i< numberOfSupportingStacks; i++)
        {
          supportingStacks[i] = new Stack<Character>();
        }
      smallestCharacter = (char) (sizeOfStartStack+1-ASCII_FOR_a); //itinialize to a large character
      stackWithNextSmallest = -1; //index of supporting stack containing the next smallest is unknown
    }

  //The addCharacterToStack adds the parameter character
  //to the start stack
  public void addCharacterToStack(char character1)
   {
       startStack.push(character1);
   }

 //The printSupportingStacks prints out the content
 //of the supporting stacks
 public void printSupportingStacks()
  {
    System.out.println("Supporting Stack Contents:\n");
    for (int i = 0; i < numberOfSupportingStacks; i++)
    {
      System.out.println("Supporting Stack " + i + ": " + supportingStacks[i].toString());
    }
    System.out.println();
  }

//The organizeCharacters method reorganizes the characters in the start stack
//into a sorted order in the final stack
public boolean organizeCharacters()
 {
   boolean success = true;

   //the next character that should move to final stack is initially 'a'
   char nextCharacterToFinalStack = 'a';

   //Print out the start stack content
   System.out.println("Start Stack Content:\n" + startStack.toString());

   while(startStack.empty() == false)
    {
          //get the next character to move
      char nextCharacter;
        
      //get(pop) the next character to move from the start stack
      //and assign it to "nextCharacter"
     
 /****1. ADD Your Code Here ****/

      if (nextCharacter == nextCharacterToFinalStack)
      {
       //if it is the next smallest character,
       //then push it onto the final stack
       
/***2. ADD Your Code Here ****/
          
       System.out.println("Move character " + nextCharacter
                        + " from start stack to final stack");

       //nextCharacterToOutputStack should be incremented now
       //to loop for the next smallest character.
       nextCharacterToFinalStack++;

       //As long as the smallest character among all supporting stacks
       //is same as the next character to move to final stack,
       //process the following:
       while (smallestCharacter == nextCharacterToFinalStack)
        {
          //look for the next smallest character among supporting stacks
          //This will compute the smallest character and which supporting stack it belongs
          fromSupportingStackToFinalStack();
          nextCharacterToFinalStack++;
        }
     }
     else
       {
                    //put the next character into one of the supporting stack
            if (putInSupportingStack(nextCharacter) == false)
              {
                success = false;
                return success;
              }
       }
    }

    System.out.println("Final Stack Content:\n" + finalStack.toString());

    return success;
 }

//The fromSupportingStackToFinalStack moves the smallest element among
//all supporting stacks into the final stack.
//It also keeps track of the next smallest character and the supporting stack
//that contains in it.
public void fromSupportingStackToFinalStack()
{
        if (stackWithNextSmallest >= 0
            && supportingStacks[stackWithNextSmallest].isEmpty() == false)
         {
      //remove(pop) the smallest character from its supporting stack
      //and move(push) to the final stack
    
  /****3. ADD Your Code Here ****/
         
      System.out.println("Move character " + smallestCharacter + " from supporting stack#"
                     + stackWithNextSmallest + " to final stack");

      printSupportingStacks();
     }

    //Find the next smallest character and the supporting stack that contains it
    //by checking the top of all supporting stacks
    smallestCharacter = (char) (sizeOfStartStack + 1 - ASCII_FOR_a);
    for (int i = 0; i < numberOfSupportingStacks; i++)
     {
      if (supportingStacks[i].isEmpty() == false
         && (supportingStacks[i].peek()).charValue() < smallestCharacter)
         {
            smallestCharacter = supportingStacks[i].peek().charValue();
            stackWithNextSmallest = i;
         }
     }
    //After the above loop, the variable "stackWithNextSmallest" should have an index
    //of the holding stack contains the next smallest character
    //AND the variable "smallestCharacter" should have the next smallestCharacter
    //to move to the final stack.
}

//The putInSupportingStack tries to push the parameter character
//into the chosen stack, i.e., the one with the top element larger
//than the parameter character and also with the top element smallest among
//such supporting stacks.
//If it cannot find such supporting stack, it returns false.
public boolean putInSupportingStack(char character2)
 {
   int chosenStackIndex = -1; //initialize to a stack index that does not exists
   char bestTop = (char) (sizeOfStartStack + 1 + ASCII_FOR_a); //initialize a larger character

   for (int i = 0; i < numberOfSupportingStacks; i++)
    {
          //look for a non-empty stack that contains its top character which is larger than
          //the parameter character to push into.
          //The index of the supporting stack with smallest top should be the chosenStackIndex
      //If the stack that you check is empty, go ahead and pick that supporting
      //stack's index as the chosenStackIndex if the chosenStackIndex was not
      //selected yet.
        
     
 /****4. ADD Your Code Here ****/
    }

    //The process cannot be completed
    //since all supporting stacks have its top character being smaller than
    //the character to be inserted.
    if (chosenStackIndex == -1)
      return false;

    //The process can continue, by pushing the parameter "character2"
    //into the supporting stack of the chosenStackIndex
    
/****5. ADD Your Code Here ****/
     
    System.out.println("Move the character " + character2 + " from start stack "
                      + "to supporting stack#" + chosenStackIndex);

    printSupportingStacks();

    //update the variable "smallestCharacter" to the parameter character2
    //and the variable "stackWithNextSmallest" to "chosenStackIndex"
    //if character2 is smaller than "smallestCharacter"
  
  /****6. ADD Your Code Here ****/

    return true;
   }

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

import java.util.Stack;

public class CharacterOrganizer {

       private Stack<Character> startStack; //stack contains characters in an order specified by a user

       private Stack<Character> finalStack; //stack to have characters in sorted order after running this algorithm

       private Stack<Character>[] supportingStacks; //stacks to hold some characters that are not in either start or final stack

       private int sizeOfStartStack; //the start stack size

       private int numberOfSupportingStacks; //number of supporting stacks, specified by a user

       private char smallestCharacter; //current smallest character that can be moved to the final stack

       private int stackWithNextSmallest; //the index of supporting stack that contains the next smallest character

       private final int ASCII_FOR_a = ((int) 'a'); //ASCII number for a, we can use it to keep track of smallest/largest characters

      

       //Constructor to initialize member variables

       public CharacterOrganizer(int sizeOfStartStack, int numOfSupportingStacks)

           {

                 startStack = new Stack<Character>();

                 finalStack = new Stack<Character>();

             this.sizeOfStartStack = sizeOfStartStack;

             this.numberOfSupportingStacks = numOfSupportingStacks;

             supportingStacks = new Stack[numberOfSupportingStacks];

             for (int i=0; i< numberOfSupportingStacks; i++)

               {

                 supportingStacks[i] = new Stack<Character>();

               }

             smallestCharacter = (char) (sizeOfStartStack+1-ASCII_FOR_a); //itinialize to a large character

             stackWithNextSmallest = -1; //index of supporting stack containing the next smallest is unknown

           }

      

       //The addCharacterToStack adds the parameter character

       //to the start stack

       public void addCharacterToStack(char character1)

          {

              startStack.push(character1);

          }

       //The printSupportingStacks prints out the content

       //of the supporting stacks

       public void printSupportingStacks()

       {

           System.out.println("Supporting Stack Contents:\n");

           for (int i = 0; i < numberOfSupportingStacks; i++)

           {

             System.out.println("Supporting Stack " + i + ": " + supportingStacks[i].toString());

           }

           System.out.println();

       }

      

       //The organizeCharacters method reorganizes the characters in the start stack

       //into a sorted order in the final stack

       public boolean organizeCharacters()

       {

          boolean success = true;

          //the next character that should move to final stack is initially 'a'

          char nextCharacterToFinalStack = 'a';

          //Print out the start stack content

          System.out.println("Start Stack Content:\n" + startStack.toString());

          while(startStack.empty() == false)

           {

                 //get the next character to move

             char nextCharacter;

              

             //get(pop) the next character to move from the start stack

             //and assign it to "nextCharacter"

           

       /****1. ADD Your Code Here ****/

             nextCharacter = startStack.pop();

             if (nextCharacter == nextCharacterToFinalStack)

             {

              //if it is the next smallest character,

              //then push it onto the final stack

             

       /***2. ADD Your Code Here ****/

                 finalStack.push(nextCharacter);

              System.out.println("Move character " + nextCharacter

                               + " from start stack to final stack");

              //nextCharacterToOutputStack should be incremented now

              //to loop for the next smallest character.

              nextCharacterToFinalStack++;

              //As long as the smallest character among all supporting stacks

              //is same as the next character to move to final stack,

              //process the following:

              while (smallestCharacter == nextCharacterToFinalStack)

               {

                 //look for the next smallest character among supporting stacks

                 //This will compute the smallest character and which supporting stack it belongs

                 fromSupportingStackToFinalStack();

                 nextCharacterToFinalStack++;

               }

            }

            else

              {

                           //put the next character into one of the supporting stack

                   if (putInSupportingStack(nextCharacter) == false)

                     {

                       success = false;

                       return success;

                     }

              }

           }

           System.out.println("Final Stack Content:\n" + finalStack.toString());

           return success;

       }

      

       //The fromSupportingStackToFinalStack moves the smallest element among

       //all supporting stacks into the final stack.

       //It also keeps track of the next smallest character and the supporting stack

       //that contains in it.

       public void fromSupportingStackToFinalStack()

       {

               if (stackWithNextSmallest >= 0

                   && supportingStacks[stackWithNextSmallest].isEmpty() == false)

                {

             //remove(pop) the smallest character from its supporting stack

             //and move(push) to the final stack

          

       /****3. ADD Your Code Here ****/

                    smallestCharacter = supportingStacks[stackWithNextSmallest].pop();

                    finalStack.push(smallestCharacter);

             System.out.println("Move character " + smallestCharacter + " from supporting stack#"

                            + stackWithNextSmallest + " to final stack");

             printSupportingStacks();

            }

              

               //Find the next smallest character and the supporting stack that contains it

               //by checking the top of all supporting stacks

               smallestCharacter = (char) (sizeOfStartStack + 1 - ASCII_FOR_a);

               for (int i = 0; i < numberOfSupportingStacks; i++)

                {

                 if (supportingStacks[i].isEmpty() == false

                    && (supportingStacks[i].peek()).charValue() < smallestCharacter)

                    {

                       smallestCharacter = supportingStacks[i].peek().charValue();

                       stackWithNextSmallest = i;

                    }

                }

               //After the above loop, the variable "stackWithNextSmallest" should have an index

               //of the holding stack contains the next smallest character

               //AND the variable "smallestCharacter" should have the next smallestCharacter

               //to move to the final stack.

           }

      

       //The putInSupportingStack tries to push the parameter character

       //into the chosen stack, i.e., the one with the top element larger

       //than the parameter character and also with the top element smallest among

       //such supporting stacks.

       //If it cannot find such supporting stack, it returns false.

       public boolean putInSupportingStack(char character2)

       {

          int chosenStackIndex = -1; //initialize to a stack index that does not exists

          char bestTop = (char) (sizeOfStartStack + 1 + ASCII_FOR_a); //initialize a larger character

          for (int i = 0; i < numberOfSupportingStacks; i++)

           {

                 //look for a non-empty stack that contains its top character which is larger than

                 //the parameter character to push into.

                 //The index of the supporting stack with smallest top should be the chosenStackIndex

             //If the stack that you check is empty, go ahead and pick that supporting

             //stack's index as the chosenStackIndex if the chosenStackIndex was not

             //selected yet.

              

           

       /****4. ADD Your Code Here ****/

                if(!supportingStacks[i].isEmpty())

                {

                       if(supportingStacks[i].peek() > character2)

                       {

                              if(supportingStacks[i].peek() < bestTop)

                              {

                                    chosenStackIndex = i;

                                    bestTop = supportingStacks[i].peek();

                              }

                       }

                }else

                {

                       if(chosenStackIndex == -1)

                       {

                              chosenStackIndex = i;

                       }

                }

           }

           //The process cannot be completed

           //since all supporting stacks have its top character being smaller than

           //the character to be inserted.

           if (chosenStackIndex == -1)

             return false;

           //The process can continue, by pushing the parameter "character2"

           //into the supporting stack of the chosenStackIndex

          

       /****5. ADD Your Code Here ****/

            supportingStacks[chosenStackIndex].push(character2);

           System.out.println("Move the character " + character2 + " from start stack "

                             + "to supporting stack#" + chosenStackIndex);

           printSupportingStacks();

           //update the variable "smallestCharacter" to the parameter character2

           //and the variable "stackWithNextSmallest" to "chosenStackIndex"

           //if character2 is smaller than "smallestCharacter"

      

       /****6. ADD Your Code Here ****/

           smallestCharacter = character2;

           stackWithNextSmallest = chosenStackIndex;

           return true;

          }

}

Add a comment
Know the answer?
Add Answer to:
Please just fill in the codes where this CharacterOrganizer.java class asks for (Bolded). It's a simple...
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
  • Now, your objective is to rewrite the same Stack class with a Generic ArrayList and make...

    Now, your objective is to rewrite the same Stack class with a Generic ArrayList and make the entire class support using Generic types. You should be able to create a Stack of any primitive wrapper class, and show us that your Generic Stack implementation (push, pop, search, display, etc.) works with: • Character (Stack) • Integer (Stack) • Float (Stack • Double (Stack) • String (Stack) You can create these Stack objects in main() and perform operations on them to...

  • I have added a little Code but I need help with the rest. /** A class...

    I have added a little Code but I need help with the rest. /** A class of stacks whose entries are stored in a chain of nodes. Implement all methods in MyStack class Main Reference : text book or class notes Do not change or add data fields */ package PJ2; public class MyStack<T> implements StackInterface<T> {    // Data fields    private Node<T> topNode; // references the first node in the chain    private int numberOfEntries;       public...

  • NO ONE HAS PROVIDED THE CORRECT CODE TO PROVIDE THE GIVEN OUTPUT. PLEASE PROVIDE CODE THAT...

    NO ONE HAS PROVIDED THE CORRECT CODE TO PROVIDE THE GIVEN OUTPUT. PLEASE PROVIDE CODE THAT WOULD CAUSE THE HW1.java TO PRINT THE RIGHT DATA.!!! The LinkedList class implements both the List interface and the Stack interface, but several methods (listed below) are missing bodies. Write the code so it works correctly. You should submit one file, LinkedList.java. Do not change the interfaces. Do not change the public method headers. Do not rename the LinkedList class. None of your methods...

  • Dynamic Implementation of Stack - The purpose is to use our dynamic implementation of stack. The...

    Dynamic Implementation of Stack - The purpose is to use our dynamic implementation of stack. The application will be to add large numbers. Review adding large numbers Remember that we can use stacks to safely add integer values that overflow the int data type g. in Java, the maximum possible int value Integer.MAX_VALUE is: 2147483647 so any int addition larger than this will overflow and fail Using stacks to add large numbers safely Will actually represent the large integers to...

  • 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...

  • I was told I need three seperate files for these classes is there anyway to tie...

    I was told I need three seperate files for these classes is there anyway to tie all these programs together into one program after doing that. I'm using netbeans btw. import java.util.ArrayList; import java.util.Scanner; /** * * */ public class MySorts {       public static void main(String[] args) {             Scanner input = new Scanner(System.in);             String sentence;             String again;             do {                   System.out                               .println("Enter a sentence, I will tell you if it is a palindrome: ");...

  • Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)   ...

    Currently, I'm getting this as my output: "Exception in thread "main" java.lang.NullPointerException    at InfixExpression.execute(InfixExpression.java:98)    at InfixExpression.Evaluate(InfixExpression.java:65)    at InfixExpression.setWholeExpr(InfixExpression.java:24)    at InfixExpression.<init>(InfixExpression.java:17)    at Main.testHW1(Main.java:17)    at Main.main(Main.java:6)" I need to get this as my output: "Testing InfixExpression: When passing null, the String and double = Infix String: , result: 0.0 When passing a valid String, the String and double = Infix String: ( 234.5 * ( 5.6 + 7.0 ) ) / 100.2, result: 29.488023952095805 ..." I...

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

    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...

  • *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;...

  • // CMPS 390 // MinHeap.java // Complete 4 methods: getMin, add, removeMin, reheap public class MinHeap...

    // CMPS 390 // MinHeap.java // Complete 4 methods: getMin, add, removeMin, reheap public class MinHeap { private Comparable a heap; // array of heap entries private static final int DEFAULT MAX SIZE = 100; private int lastIndex; // index of last entry public MinHeap() { heap = new Comparable (DEFAULT_MAX_SIZE]; lastIndex = 0; } // end default constructor public MinHeap (int maxSize) { heap = new Comparable (maxSize); lastIndex = 0; } // end constructor public MinHeap (Comparable[] entries)...

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
ADVERTISEMENT