Question

In: Computer Science

in Java please For this assignment you are to write a class that supports the addition...

in Java please

For this assignment you are to write a class that supports the addition of extra long integers, by using linked-lists. Longer than what is supported by Java's built-in data type, called long.

Your program will take in two strings, consisting of only digits, covert each of them to a linked-list that represents an integer version on that string. Then it will create a third linked-list that represents the sum of both of the linked lists. Lastly, it will print out the result of the sum.

Conceptual Example
For the string: "12", create a list: head->1->2->null
For the string: "34", create a list: head->3->4->null
Add the two lists to create a third list: head->4->6->null
print the resulting linked list as "46"
Where "->" represents a link.

Keep in mind that the conceptual example above is conceptual. It does suggest a certain implementation. However as you read on you will see that you have several options for implementing your solution. You need not use the suggested implementation above.

For this class you are to implement a minimum of three methods. They are:

  1. A method called makeSDList() that takes in a string, consisting only of digits, as an argument, and creates and returns a linked-link representation of the argument string.

    The method has the following header:

    SDList makeSDList(String s) { }

    where s is a string, and SDList is the class name of the linked list.  

  2. A method called addLists() that takes takes two lists, adds them together, and creates and returns a list that represents the sum of both argument lists.

    The method has the following header:

    SDList addLists(SDList c) { }

    wherec  linked-list of type SDList .

  3. A method called displayList() that takes takes a list, prints the value of each digit of the list.  

    The method has the following header:

    void displayList() { }

Programming Notes

  1. You need not add any methods you don't need.
  2. You can add any methods use wish.
  3. You can use any type of linked list like: singly-linked, doubly-linked, circular, etc.
  4. You can choose you own list implementation such-as with or without sentinels, with head and/or tail points, etc.
  5. Do not assume any maximum length for either addend.
  6. You can assume that an each addend is a least one digit long.
  7. You need not test for the null or empty string ("") cases.
  8. The addends need not be the same length.

Programming Rules:

  1. You are not allowed to change the signature of the three methods above.
  2. You are not allowed to use arrays or ArrayLists anywhere in your solution.
  3. You are not allowed to use any Java built-in (ADTs), such as Lists, Sets, Maps, Stacks, Queues, Deques, Trees, Graphs, Heaps, etc. Or make any class that inherits any of those ADTs.
  4. You are to create your own node and list class. For your node and list class you can use the code that was used in the book, video and lecture notes related to the node and lists class examples.
  5. You are only allowed to have one class for your nodes and one class for your lists.
  6. You are not allowed to use Java Generics.
  7. You can use any data type to represent the digits (in the node). However, each node must represent one and only one digit.
  8. If hard-coding detected in any part of your solution your score will be zero for the whole assignment.

Submission Rules:

1. Submit only one Homework5.java file for all test cases. The starter file is names Homework5a.java so you will need rename the file before you begin submitting your solution.

2. Anything submitted to Mimir is considered to be officially submitted to me and is considered to be 100% your work. Even if it is not your last planned submission.

3. Any extra testing code that you wrote and used to do your own testing should be deleted from the file that gets used in the final grading. I emphasize the word deleted. Commenting out code is not sufficient and not considered deleted. It must be completely removed. English comments written to explain your code are perfectly fine.

Solutions

Expert Solution

I have implemented Homework5.java with two classes which represents singly linkedlist where each node of singly linkedlist represents a single digit.

Classes:-

1> SDList :- This class represents a singly linked list.

2> ListNode :- This class represents a node of singly linked list.

Program :-

import java.util.Scanner;

public class Homework5 {
    
    public static void main(String[] args) {
        
        // create reference of SDList class
        SDList x, y, z;
        
        String a, b;
        Scanner input = new Scanner(System.in); // Create a Scanner object
        
        try{
            // get the number from the user
            System.out.print("A: ");
            a = input.nextLine();
            
            // keep only digits and remove other characters from the String
            String first = "";
            for(int i=0; i<a.length(); i++){
                
                // append digits only
                if(Character.isDigit(a.charAt(i))){
                    
                    // append into the string
                    first += String.valueOf(a.charAt(i));
                }
                    
            }
            x = makeSDList(first); // convert first string to a linked list

            // get the number from the user
            System.out.print("\nB: ");   
            b = input.nextLine();
            
            // keep only digits and remove other characters from the String
            String second = "";
            for(int i=0; i<b.length(); i++){
                
                // append digits only
                if(Character.isDigit(b.charAt(i))){
                    
                    // append into the string
                    second += String.valueOf(b.charAt(i));
                }
                    
            }
 
            y = makeSDList(second); // convert second string to a linked list
        
            z = x.addLists(y); // add lists x & y and store result in list y

            System.out.print("\nA+B: ");

            z.displayList(); // call function that displays list z

            System.out.println();
            
        }finally{
            input.close();
        }
    }

    
    // This method return singly linkedlist by converting string of digits.
    public static SDList makeSDList(String s) {
    
        // first crate a  SDList object
        SDList sdlist = new SDList();
        
        // store each digit in linkedlist using for loop
        for(int i=0; i<s.length(); i++){
             
            // get each digit from the string and convert it into the integer
            // first get the character and convert it into the string
            String digit = String.valueOf(s.charAt(i));
                
            // and then convert into the integer
            int item = Integer.parseInt(digit);
                        
            // here, at "0"th iteration we have to create first node as a head
            if(i==0){
                
                // create first node as a head node
                // call the addFirst() method
                sdlist.addFirst(item);
                    
            }else{
                
                // when newNode is not a first node
                // call the addLast(0 method
                sdlist.addLast(item);
            }
        }
       
        return sdlist;
    }
}


// This class represents a Singly Linkedlist
class SDList {

    // points to the first node of linkedlist
    ListNode head;
    
    // This class reprent a node for linkedlist
    class ListNode{
        
        int item;
        ListNode next;
        
        public ListNode(){}
        
        // constructor which create a node for likedlist
        public ListNode(int item){
            
            // store the number
            this.item = item;
            
            this.next = null;
        }
    }
        
    
    // This method add a newNode as a first node for the linkedlist
    public void addFirst(int item){
            
        // create newNode by creating object of ListNode class
        ListNode firstNode = new ListNode(item);
            
        // make newNode as a head
        head = firstNode;
    }
        
    
    // This method add a newNode at the end of the linkedlist
    public void addLast(int item){
            
        // create newNode by creating object of ListNode class
        ListNode newNode = new ListNode(item);
            
        // reach at the last node of linkedlist
        ListNode curr = head;
            
        while(curr.next != null){
                
            // goto the next node
            curr = curr.next;
        }
            
        // here we reach to the last node
        // now add the newNode into the curr.next
        curr.next = newNode;
            
    }
    
    
    // This method add the two singly linkedlist
    public SDList addLists(SDList c) {   
        
        // store head of first list
        ListNode list1 = this.head;
        
        // store head of second list
        ListNode list2 = c.head;
        
        // create resultant list
        SDList resultList = new SDList();
        
        // create head as a "0" for creating list
        resultList.head = new ListNode(0);
        
       
        // store the carry after adding two digits of two linkedlist
        int carry=0;
        
        // store the sum of two digits of two linkedlist
        int sum;
        
        while(list1 !=null || list2 != null){
            /* 
                In addiition procees, if fist list become null
                then add zero(0) with the second list node
            */
            if(list1 == null){
                
                // do the addition
                sum = carry + 0 + list2.item;
                
                // after addition, go to the next node
                list2 = list2.next;
            }
            else if(list2 == null){
                
                // do the addition
                sum = carry + 0 + list1.item;
                
                // after addition, go to the next node
                list1 = list1.next;

            }
            else{
                
                // when two list does not contain null node
                // do the addition for node of fist and node of second linkedlist
                sum = carry + list1.item + list2.item;
                
                // after addition, go to the next node
                list1 = list1.next;
                list2 = list2.next;

            }
            
            // store carray after addition
            carry=sum/10;
            
            // store the answer of addition to the newNode 
            resultList.addLast(sum % 10);
          
        }
        
        // after addition if the carry is generated then add to the end of list
        if(carry > 0){
            
            // addLast() method
            resultList.addLast(carry);
        }
        
        // now set head to the first added node
        resultList.head = resultList.head.next;
        
        // return the resultant list
        return resultList; 
    }

    
    // This method display the whole linkedlist
    public void displayList() {
        
        // stor head into the curr
        ListNode curr = head;
        
        //display each node using while loop
        while(curr != null){
            
            // display the result linkedlist
            System.out.print(curr.item);
            
            // goto the next node
            curr = curr.next;
        }
    }
}

Output:-

1> Entered string with only digits.

2> Entered string with space and digits also.

According to the output, we can see that our program give the perfect result of  addition of two numbers( singly linkedlist) if the entered string contains any character except the digits that are entered by the user.

I hope you will understand the above program.

Do you feel needful and useful then please upvote me.

Thank you.


Related Solutions

Long Integer Addition For this assignment you are to write a class that supports the addition...
Long Integer Addition For this assignment you are to write a class that supports the addition of extra long integers, by using linked-lists. Longer than what is supported by Java's built-in data type, called long. Your program will take in two strings, consisting of only digits, covert each of them to a linked-list that represents an integer version on that string. Then it will create a third linked-list that represents the sum of both of the linked lists. Lastly, it...
Write the class Complex that supports the basic complex number operations. Such operations are addition (+),...
Write the class Complex that supports the basic complex number operations. Such operations are addition (+), subtraction (-) and multiplication (*) of complex numbers, and multiplication (*) of a complex by a scalar (float or int). All methods must return (not print) the result. Class also supports the rich comparison for equality (= =) - Check the doctest for object behavior examples. - You must use the special methods for those 4 operators in order to override their behavior -...
Begin by creating a Java project with one class – Addition. Start with the class Addition...
Begin by creating a Java project with one class – Addition. Start with the class Addition as shown in Figure 12.2. This program uses dialog boxes for I/O to get two integers and display the result of adding them together. The program should run “as is”. Change the program so that it gets and adds two doubles instead of integers. When that is working get a third double using a dialog box. Add the three doubles together, and display the...
In Java please. Thank you! Recursion For this assignment you are going to write six different...
In Java please. Thank you! Recursion For this assignment you are going to write six different methods. Each method is to be written recursively. Any method that is written iteratively will not receive any credit, even if it is correct and produces the same results or output. You will be given a starter file. You are not allowed to change the signatures of any of the given methods. You are not allowed to add any methods to your solutions. Write...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class,...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class, you are to have the following data members: name: String (5 pts) id: String   (5 pts) hours: int   (5 pts) rate: double (5 pts) private members (5 pts) You are to create no-arg and parameterized constructors and the appropriate setters(accessors) and getters (mutators). (20 pts) The class definition should also handle the following exceptions: An employee name should not be empty, otherwise an exception...
**JAVA LANGUAGE** This assignment will use the Employee class that you developed for assignment 6. Design...
**JAVA LANGUAGE** This assignment will use the Employee class that you developed for assignment 6. Design two sub- classes of Employee...FullTimeEmployee and HourlyEmployee. A full-time employee has an annual salary attribute and may elect to receive life insurance. An hourly employee has an hourly pay rate attribute, an hours worked attribute for the current pay period, a total hours worked attribute for the current year, a current earnings attribute (for current pay period), a cumulative earnings attribute (for the current...
Coding Java Assignment Write the following static methods. Assume they are all in the same class....
Coding Java Assignment Write the following static methods. Assume they are all in the same class. Assume the reference variable input for the Scanner class and any class-level variables mentioned are already declared. All other variables will have to be declared as local unless they are parameter variables. Use printf. A method that prompts for the customer’s name and returns it from the keyboard. A method called shippingInvoice() that prompts for an invoice number and stores it in a class...
0. Introduction. In this assignment you will implement a stack as a Java class, using a...
0. Introduction. In this assignment you will implement a stack as a Java class, using a linked list of nodes. Unlike the stack discussed in the lectures, however, your stack will be designed to efficiently handle repeated pushes of the same element. This shows that there are often many different ways to design the same data structure, and that a data structure should be designed for an anticipated pattern of use. 1. Theory. The most obvious way to represent a...
java For this assignment, you will create a Time class that holds an hour value and...
java For this assignment, you will create a Time class that holds an hour value and a minute value to represent a time. We will be using "military time", so 12:01 AM is 0001 and 1 PM is 1300. For this assignment, you may assume valid military times range from 0000 to 2359. Valid standard times range from 12:00 AM to 11:59 PM. In previous assignments, we had a requirement that your class be named Main. In this assignment, the...
Please write the program in JAVA and provide me with the output screenshots!! Assignment Objectives •...
Please write the program in JAVA and provide me with the output screenshots!! Assignment Objectives • Be able to write methods • Be able to call methods Introduction Methods are commonly used to break a problem down into small manageable pieces. A large task can be broken down into smaller tasks (methods) that contain the details of how to complete that small task. The larger problem is then solved by implementing the smaller tasks (calling the methods) in the correct...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT