Question

A stack can be used to print numbers in other bases (multi-base output). Examples: (Base8) 2810...

  1. A stack can be used to print numbers in other bases (multi-base output).

Examples:

  1. (Base8) 2810 = 3 * 81 + 4 * 80 = 348
  2. (Base4) 7210 = 1 * 43 + 0 * 42 + 2 * 41 + 0 * 4 = 10204
  3. (Base 2) 5310 = 1 * 25 + 1*24 + 0 * 23 + 1 * 22 + 0 * 21 + 1 * 20 = 1101012

Write a java program using stacks that take 3 non-negative (base 10) long integer numbers, and a base B (B is in the range 2–9) and writes the number to the screen as a base B number. The program prompts the user for 3 numbers and bases and then outputs them.

Use as input:

  1. 7210            Base 4
  2. 5310            Base 2
  3. 355310       Base 8
  1. Show the ListStackADT<T> interface
  1. Create a ListStackDataStrucClass<T> with the following methods: default constructor, overloaded constructor, copy constructor, getTop, setTop, isEmpty, ifEmpty (if empty throw the exception), push, peek, pop, toString.

  1. Create a private inner class of ListStack<T> called StackNode<T> with the following methods: default constructor, overloaded constructor, copy constructor, getValue, getNext, setValue, setNext

  1. Create a BaseConverter class (non-generic) with the following methods: default constructor, inputPrompt, convert [converts a BaseNumber to a converted String], convertAll [instantiate a String object] , toString, processAndPrint

  1. Create a private inner class BaseNumber. The inner class has the following methods: default constructor, overloaded constructor, getNumber, getBase, setNumber, setBase. [Make your private instance variables in the inner class Long type].

  1. Create a BaseConverterDemo class that only has 2 statements: Create a BaseConverter object and then have it invoke processAndPrint.

  1. Exception classes: StackException, EmptyStackException, FullStackException

Homework Answers

Answer #1

// StackException.java

public class StackException extends Exception {

      /**

      * Default constructor

      */

      public StackException(String msg) {

            super(msg);

      }

}

// EmptyStackException.java

public class EmptyStackException extends StackException {

      /**

      * Default constructor

      */

      public EmptyStackException() {

            super("Stack is empty.");

      }

}

// FullStackException.java

public class FullStackException extends StackException {

      /**

      * Default constructor

      */

      public FullStackException() {

            super("Stack is full.");

      }

}

// ListStackADT.java

public interface ListStackADT<T> {

      public boolean isEmpty();

      public void push(T value);

      public T pop() throws EmptyStackException;

      public T peek() throws EmptyStackException;

}

// ListStackDataStrucClass.java

/**

* This class represents a stack

*/

public class ListStackDataStrucClass<T> implements ListStackADT<T> {

      // Inner class

      class StackNode {

            // Data fields

            private T value;

            private StackNode next;

            /**

            * Default constructor

            */

            public StackNode() {

                  this.value = null;

                  this.next = null;

            }

            /**

            * Overloaded constructor

            *

            * @param value

            *            - value of the node

            * @param next

            *            - next node

            */

            public StackNode(T value, StackNode next) {

                  this.value = value;

                  this.next = next;

            }

            /**

            * Copy constructor

            *

            * @param node

            *            - Stack node

            */

            public StackNode(StackNode node) {

                  this.value = node.getValue();

                  this.next = node.getNext();

            }

            /**

            * @return - the value

            */

            public T getValue() {

                  return value;

            }

            /**

            * @return - the next node

            */

            public StackNode getNext() {

                  return next;

            }

            /**

            * Sets the value

            *

            * @param value

            *            - the value to set

            */

            public void setValue(T value) {

                  this.value = value;

            }

            /**

            * Sets the next node

            *

            * @param next

            *            - the next to set

            */

            public void setNext(StackNode next) {

                  this.next = next;

            }

      }

      // Data fields for ListStackDataStrucClass

      private StackNode top;

      /**

      * Default constructor

      */

      public ListStackDataStrucClass() {

            this.top = null;

      }

      /**

      * Overloaded constructor

      */

      public ListStackDataStrucClass(StackNode node) {

            this.top = node;

      }

      /**

      * Copy constructor

      */

      public ListStackDataStrucClass(ListStackDataStrucClass stack) {

            // Set top as empty

            setTop(null);

            try {

                  // Check if stack is not empty

                  if (!stack.isEmpty()) {

                        // Copy elements form stack to this stack

                        while (!stack.isEmpty())

                              push((T) stack.pop());

                  }

            } catch (EmptyStackException e) {

                  System.out.println(e.getMessage());

            }

      }

      /**

      * @return - the top node

      */

      public StackNode getTop() {

            return top;

      }

      /**

      * Sets the top node

      *

      * @param top

      *            - the top to set

      */

      public void setTop(StackNode top) {

            this.top = top;

      }

      /**

      * Checks whether the stack is empty

      *

      * @return - returns true if stack is empty, false otherwise

      */

      public boolean isEmpty() {

            return (getTop() == null);

      }

      /**

      * Throws exception if stack is empty

      *

      * @throws EmptyStackException

      *             - if stack is empty

      */

      public void ifEmpty() throws EmptyStackException {

            if (isEmpty())

                  throw new EmptyStackException();

      }

      /**

      * Adds a value to the stack

      *

      * @param value

      *            - value to be inserted

      */

      public void push(T value) {

            // Check if stack is empty

            if (isEmpty())

                  setTop(new StackNode(value, null));

            else {

                  // Create new node

                  StackNode newNode = new StackNode(value, getTop());

                  // Set newNode as the top

                  setTop(newNode);

            }

      }

      /**

      * Returns and remove the top node from the stack

      *

      * @return - Returns the top node in the stack

      * @throws EmptyStackException

      *             - if stack is empty

      */

      public T pop() throws EmptyStackException {

            if (isEmpty())

                  throw new EmptyStackException();

            else {

                  T value = getTop().getValue();

                  // Set new top

                  setTop(getTop().getNext());

                  return value;

            }

      }

      /**

      * Returns but does not remove the top node from the stack

      *

      * @return - Returns the top node in the stack

      * @throws EmptyStackException

      *             - if stack is empty

      */

      public T peek() throws EmptyStackException {

            if (isEmpty())

                  throw new EmptyStackException();

            else

                  return getTop().getValue();

      }

      /**

      * Returns the stack contents

      */

      @Override

      public String toString() {

            StringBuffer sb = new StringBuffer();

            sb.append("[ ");

            // Check if stack is not empty

            if (!isEmpty()) {

                  StackNode node = getTop();

                  // Traverse through the stack

                  while (node != null) {

                        sb.append(node.getValue() + " ");

                  }

            }

            sb.append("]");

            return sb.toString();

      }

}

// BaseConverter.java

import java.util.Scanner;

public class BaseConverter {

      // Inner class

      class BaseNumber {

            // Data fields

            private long number;

            private long base;

            /**

            * Default constructor

            */

            public BaseNumber() {

                  this.number = 0;

                  this.base = 10;

            }

            /**

            * Overloaded constructor

            *

            * @param number

            *            - number

            * @param base

            *            - base to which the number is to be converted

            */

            public BaseNumber(long number, long base) {

                  this.number = number;

                  this.base = base;

            }

            /**

            * @return - the number

            */

            public long getNumber() {

                  return number;

            }

            /**

            * @return - the base

            */

            public long getBase() {

                  return base;

            }

            /**

            * @param number

            *            - the number to set

            */

            public void setNumber(long number) {

                  this.number = number;

            }

            /**

            * @param base

            *            - the base to set

            */

            public void setBase(long base) {

                  this.base = base;

            }

      }

      private static final int MIN_BASE = 2;

      private static final int MAX_BASE = 9;

      private static final int NUM = 3;

      // Data fields for BaseConverter class

      private BaseNumber[] baseNumber;

      /**

      * Default constructor

      */

      public BaseConverter() {

            baseNumber = new BaseNumber[NUM];

            // Get base number

            inputPrompt();

      }

      /**

      * Gets a number and its base and sets the base number

      */

      private void inputPrompt() {

            // Scanner to get user input

            Scanner in = new Scanner(System.in);

            // Get NUM base numbers

            for (int i = 0; i < NUM; i++) {

                  System.out.println("Number " + (i + 1));

                  // Get number

                  long number = -1;

                  while (number < 0) {

                        System.out.print("Enter a positive integer: ");

                        number = in.nextLong();

                  }

                  // Get base

                  long base = -1;

                  while ((MIN_BASE > base) || (base > MAX_BASE)) {

                        System.out.print("Enter output base[" + MIN_BASE + " - " + MAX_BASE + "]: ");

                        base = in.nextLong();

                  }

                  // Set base number

                  baseNumber[i] = new BaseNumber(number, base);

                  System.out.println();

            }

      }

      /**

      * Converts the base 10 number to target base and returns it.

      * @param bNumber - number to be converted to a base

      */

      private String convert(BaseNumber bNumber) {

            // Get base 10 number

            long number = bNumber.getNumber();

            // Get target base

            long targetBase = bNumber.getBase();

            // Create stack to hold data

            ListStackDataStrucClass<Long> stack = new ListStackDataStrucClass<Long>();

            // Convert

            while (number != 0) {

                  // Push number % targetBase into stack

                  stack.push(number % targetBase);

                  // Set number

                  number = number / targetBase;

            }

            // Get the number converted to base

            StringBuffer sb = new StringBuffer();

            // Get contents from stack

            while (!stack.isEmpty())

                  try {

                        sb.append(stack.pop());

                  } catch (EmptyStackException ese) {

                        System.out.println(ese.getMessage());

                  }

            return sb.toString();

      }

      /**

      * Converts NUM BaseNumber(s) to target bases

      */

      private String convertAll() {

            String result = new String();

           

            // Convert all NUM BaseNumber to target base

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

                  result = result + (baseNumber[i].getNumber() + " (Base 10) = " + convert(baseNumber[i]) + " (Base " + baseNumber[i].getBase() + ")\n");

           

            return result;

      }

      public String toString() {

            return convertAll();

      }

      public void processAndPrint() {

            System.out.println(this);

      }

}

// BaseConverterDemo.java

public class BaseConverterDemo {

      public static void main(String[] args) {

            // Create BaseConverter object

            BaseConverter baseConv = new BaseConverter();

            baseConv.processAndPrint();

      }

}

SAMPLE OUTPUT:

if this answer is helpful to you please give positive rating.if any doubts please provide comment i will try to clarify your doubts.

Know the answer?
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
Similar Questions
c++ C++ CLASSES and objects DO ADD COMMENTS DISPLAY OUTPUT First make three files: episode.cpp, episode.h...
c++ C++ CLASSES and objects DO ADD COMMENTS DISPLAY OUTPUT First make three files: episode.cpp, episode.h andRun.cpp to separate class header and implementation. In this program, we are going to create a small scale Telivision Management System. A) Create a class Episode with following variables: char* episode_name, char* episode_venue, char episode_date[22] and char episode_time[18]. Input format for episode_date: dd-mm-yyyy Input format for episode_time: hh:mm am/pm B) Implement default constructor and overloaded constructor. Print “Default Constructor Called” and “Overloaded Constructor Called”...
The following is for a Java Program Create UML Class Diagram for these 4 java classes....
The following is for a Java Program Create UML Class Diagram for these 4 java classes. The diagram should include: 1) All instance variables, including type and access specifier (+, -); 2) All methods, including parameter list, return type and access specifier (+, -); 3) Include Generalization and Aggregation where appropriate. Java Classes description: 1. User Class 1.1 Subclass of Account class. 1.2 Instance variables __ 1.2.1 username – String __ 1.2.2 fullName – String __ 1.2.3 deptCode – int...
Lab: RectClass (constructor) Code in C++ This program creates a Rectangle object, then displays the rectangle's...
Lab: RectClass (constructor) Code in C++ This program creates a Rectangle object, then displays the rectangle's length, width, and area Define an overloaded constructor and use it when creating the Rectangle object instead of using the setters. Change this program to calculate and display the rectangle's perimeter. Example: In feet, how wide is your house? 20 In feet, how long is your house? 25 The house is 20.00 feet wide. The house is 25.00 feet long. The house has 500.00...
C# Step 1: Create a Windows Forms Application. Step 2: Create a BankAccount class. Include: Private...
C# Step 1: Create a Windows Forms Application. Step 2: Create a BankAccount class. Include: Private data fields to store the account holder's name and the account balance A constructor with 0 arguments A constructor with 1 argument (account holder's name) A constructor with 2 arguments(account holder's name and account balance) Public properties for the account holder's name and the account balance. Do not use auto-implemented properties. A method to increase the balance (deposit) A method to decrease the balance...
Cpp Task: Create a class called Mixed. Objects of type Mixed will store and manage rational...
Cpp Task: Create a class called Mixed. Objects of type Mixed will store and manage rational numbers in a mixed number format (integer part and a fraction part). Details and Requirements Your class must allow for storage of rational numbers in a mixed number format. Remember that a mixed number consists of an integer part and a fraction part (like 3 1/2 – “three and one-half”). The Mixed class must allow for both positive and negative mixed number values. A...
This is the java code that I have, but i cannot get the output that I...
This is the java code that I have, but i cannot get the output that I want out of it. i want my output to print the full String Form i stead of just the first letter, and and also print what character is at the specific index instead of leaving it empty. and at the end for Replaced String i want to print both string form one and two with the replaced letters instead if just printing the first...
Java Program Implement a class called AnimalTrainer. Include the following data types in your class with...
Java Program Implement a class called AnimalTrainer. Include the following data types in your class with the default values denoted by dataType name : defaultValue - String animal : empty string - int lapsRan : 0 - boolean resting : false - boolean eating : false - double energy : 100.00 For the animal property implement both getter/setter methods. For all other properties implement ONLY a getter method Now implement the following constructors: 1. Constructor 1 – accepts a String...
Homework 3 Before attempting this project, be sure you have completed all of the reading assignments,...
Homework 3 Before attempting this project, be sure you have completed all of the reading assignments, hands-on labs, discussions, and assignments to date. Create a Java class named HeadPhone to represent a headphone set. The class contains:  Three constants named LOW, MEDIUM and HIGH with values of 1, 2 and 3 to denote the headphone volume.  A private int data field named volume that specifies the volume of the headphone. The default volume is MEDIUM.  A private...
TrackMinMax For this lab, you will create a generic version of the IntTrackMinMax class you wrote...
TrackMinMax For this lab, you will create a generic version of the IntTrackMinMax class you wrote in a previous lab, called TrackMinMax. The API is: Function Signature Description constructor TrackMinMax() constructor check void check(T i) compares i to the current minimum and maximum values and updates them accordingly getMin T getMin() returns the minimum value provided to check() so far getMax T getMax() returns the maximum value provided to check() so far toString String toString() returns the string "[min,max]" As...
In C++ Employee Class Write a class named Employee (see definition below), create an array of...
In C++ Employee Class Write a class named Employee (see definition below), create an array of Employee objects, and process the array using three functions. In main create an array of 100 Employee objects using the default constructor. The program will repeatedly execute four menu items selected by the user, in main: 1) in a function, store in the array of Employee objects the user-entered data shown below (but program to allow an unknown number of objects to be stored,...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT