Question

I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT w...

I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths.

Project requirements:

.

Use a Stack ADT with the implementation of your choice (Array or Link), it should not make a

difference

2.Read two “integer” numbers from the user. Hint: You don’t need to use an int type when you read, it may be easier to parse the input as a string

and convert to int as you push to the stack

3. Ask user for the maximum length of the digits if necessary (depends on your structure’s boundedness).

4. Use the algorithm discussed in class to simulate the addition of the two numbers

a. Push digits of number1 in stack 1

b. Push digits of number2 in stack 2

c. Numbers may or may not be of the same length. Also number2 may be longer or shorter. You should be able to handle all cases.

d. Rough algorithm below:

Repeat as long as there is something to pop

•Pop digits and add

(including the carry over if one exists)

•Place result in output stack, one digit only, so if sum is 14, place the 4 in the output stack and

• “Carry over” if necessary , in the example above, carry over the 1 and use it in the next addition

e. Display result of sum

f. Handle having numbers of different digit lengths – so if you are popping elements from number stacks of different sizes, your checks should take that into account

CODE:

package AddStack;

public class ArrayStack<T> implements BoundedStackInterface<T> {

   private int top;
   private T[] stack;
   private static final int DEFCAP = 100;  
  
   public ArrayStack() {
       this(DEFCAP);
   }
  
   public ArrayStack(int capacity) {
       stack = (T[]) new Object[capacity];
       top = -1;
   }
  
   @Override
   public T pop() throws StackUnderflowException {
       // TODO Auto-generated method stub
       T element;
       if (isEmpty())
           throw new StackUnderflowException("Pop attempted on an empty stack");
       else {
           element = stack[top];
           stack[top] = null;
           top--;
           return element;
       }

   }

   @Override
   public T peek() throws StackUnderflowException {
      
   if(isEmpty()) {
       throw new StackUnderflowException("no elements in stack");
       }
  
   return stack[top];
  
   }

   @Override
   public boolean isEmpty() {
       // TODO Auto-generated method stub
       return (top == -1);
   }

   @Override
   public int size() {
       return top;
   }

   @Override
   public void push(T element) throws StackOverflowException {
       // TODO Auto-generated method stub
      
       if (isFull())
           throw new StackOverflowException("Push attempted on a full stack");
       else {
          
           top++;
           stack[top] = element;
          
       }
      
   }

   @Override
   public boolean isFull() {
       // TODO Auto-generated method stub
       return (top == stack.length-1);
   }
  
   public T inspect(int loc) {
  
   if(loc > size()) {
   return null;
   }
  
   return stack[loc];
  
   }
  
  
   public int capacity() {
  
   return stack.length;
   }

}

package AddStack;
import java.io.IOException;
import java.util.Scanner;

public class AddMain {

   static Scanner sc;

   public static void main(String[] args) throws IOException, StackUnderflowException {

       sc = new Scanner(System.in);
       System.out.print("\tEnter an option (1) to Add, (2) Quit ");
       String input = sc.nextLine();

       while (!input.equals("2")) {

           if (input.equals("1")) {

               ArrayStack<Integer> sum = new ArrayStack<Integer>();
               System.out.print("\tEnter integer. Enter -1 to stop: ");
               input = sc.nextLine();

               while (!input.equals("-1")) {
                   ArrayStack<Integer> number = new ArrayStack<Integer>();
                   for (int i = 0; i < input.length(); i++) {
                       number.push(Integer.parseInt(String.valueOf(input.charAt(i))));
                  
                   }
              
                   sum = add(sum, number);
                   System.out.print("\tEnter integer. Enter -1 to stop. => ");
                   input = sc.nextLine();
               }

               String result = "";
               while (!sum.isEmpty()) {
                   result = sum.peek() + result;
                   sum.pop();
               }

               System.out.println("The sum is: " + result);

           } else {
               System.out.println("Invalid option " + input);
           }

           System.out.print("\tEnter an option (1) to add, (2) to Quit ");
           input = sc.nextLine();
       }

   }

   public static ArrayStack<Integer> add(ArrayStack<Integer> first, ArrayStack<Integer> second) throws StackUnderflowException {

       ArrayStack<Integer> sum = new ArrayStack<Integer>();
       int firstInteger;
       int secondInteger;
       int carryOver = 0;
       while (!first.isEmpty() && !second.isEmpty()) {

           firstInteger = (int) first.peek();
           first.pop();

           secondInteger = (int) second.peek();
           second.pop();

           int total = firstInteger + secondInteger + carryOver;
           if (total >= 10) {
               total -= 10;
               carryOver = 1;
           } else {
               carryOver = 0;
           }
           sum.push(total);
       }
       if (first.isEmpty() && second.isEmpty()) {

           if (carryOver > 0) {
               sum.push(carryOver);
               carryOver = 0;
           }
       } else if (first.isEmpty()) {

           while (!second.isEmpty()) {

               sum.push((int) second.peek() + carryOver);
               second.pop();
               carryOver = 0;
           }
       } else {

           while (!first.isEmpty()) {
               sum.push((int) first.peek() + carryOver);
               first.peek();
               carryOver = 0;
           }
       }

       ArrayStack<Integer> realSum = new ArrayStack<Integer>();
       while (!sum.isEmpty()) {
           realSum.push((Integer) sum.peek());
           sum.pop();
       }
       return realSum;
   }

}

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

Hope this is what you need help with. Updated code for adding two stack values:

while (!first.isEmpty() && !second.isEmpty()) {

firstInteger = (int) first.peek();
first.pop();

secondInteger = (int) second.peek();
second.pop();

int total = firstInteger + secondInteger + carryOver;
if (total%10) {
//total -= 10;
//carryOver = 1;
              carryOver=total/10;
               total=total%10;
} else {
carryOver = 0;
}
sum.push(total);
}

Add a comment
Know the answer?
Add Answer to:
I have a java project that I need help trying to finish. I have most of it completed but the issue I am running into is adding numbers with different lengths. Project requirements: . Use a Stack ADT w...
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
  • Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns...

    Suppose we decide to add a new operation to our Stack ADT called sizeIs, which returns a value of primitive type int equal to the number of items on the stack. The method signature for sizeIS is public int sizeIs() a.) Write the code for sizeIs for the ArrayStack class b.) Write the code for sizeIs for the LinkedStack class (do not add any instance variables to the class; each time sizeIs is called you must "walk" through the stack...

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

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

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

  • I have a Graph.java which I need to complete four methods in the java file: completeGraph(),...

    I have a Graph.java which I need to complete four methods in the java file: completeGraph(), valence(int vid), DFS(int start), and findPathBFS(int start, int end). I also have a JUnit test file GraphTest.java for you to check your code. Here is Graph.java: import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; /* Generic vertex class */ class Vertex<T> { public T data; public boolean visited; public Vertex() { data = null; visited = false; } public Vertex(T _data) { data =...

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

  • Stack help. I need help with my lab assignment. Complete a method for a class named...

    Stack help. I need help with my lab assignment. Complete a method for a class named Palindrome that evaluates a string phrase to determine if the phrase is a palindrome or not. A palindrome is a sequence of characters that reads the same both forward and backward. When comparing the phrase to the same phrase with the characters in reverse order, an uppercase character is considered equivalent to the same character in lowercase, and spaces and punctuation are ignored. The...

  • I need help with this code This is what I need to do: Implement the Stack...

    I need help with this code This is what I need to do: Implement the Stack Class with an ArrayList instead of an array, including the following functions: • empty • push • peek • pop • overrided toString( ) function which returns all of the stack’s contents Things to note: • You no longer need a size. • You no longer need to define a constant DEFAULT_CAPACITY. Since ArrayLists grow dynamically. • Whenever possible, use ArrayList functions instead of...

  • Return a method as an expression tree Hi guys. I need to return a method as...

    Return a method as an expression tree Hi guys. I need to return a method as an expression tree, it's currently returning null. public static ExpressionTree getExpressionTree(String expression) throws Exception {       char[] charArray = expression.toCharArray(); Node root = et.constructTree(charArray); System.out.println("infix expression is"); et.inorder(root); return et; } In the above method, et needs to have a value. -- Take a look at the complete class below. Kindly assist. ; public class ExpressionTree extends BinaryTree { private static final String DELIMITERS...

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