Question

In: Computer Science

Modify listarr.java program by adding the following 2 methods: public void insertsorted(x); // Inert x in...

Modify listarr.java program by adding the following 2 methods:

public void insertsorted(x); // Inert x in a sorted list.

protected int binsearch(x); // Binary search for x

Assume you have a data file p1.txt with the following contents:

8    

4 15 23 12 36 5 36 42

3

5 14 36

and your main program is in p1.java file.

To compile: javac p1.java

To execute: java p1 < any data file name say p1.txt

Your output should be formatted (i.e. using %4d for print) as follow:

Your name:……………………………. Student ID:…………………………

The 8 inserted data are as follow:

4 5 12 15 23 36 36 42

Searching for 3 data in the sorted list.

5: is found!

14: Ooops is not in the list?

36: is found!

Your main method should be as follow:

public static void main(String args[]) {

int j, n, m, k, x;

try{

          Scanner inf = new Scanner(System.in);                 

          n = inf.nextInt();// read No. of data to read

         

          // Create a List of type Integer of size n

          listarr Lint = new listarr(n);      

         

          // Read n element and insert in a sorted listposition randomly in the list

          for(j = 1; j <= n; j++){

                    x = inf.nextInt(); // read element

                    Lint.insertsorted (x);

          }

         

          System.out.printf(“The %d inserted data are as follow:”, n);

          System.out.print(Lint.toString());

          // read No. of data to search

          m = inf.nextInt();

          for(j = 1; j <= m; j++){

                    x = inf.nextInt(); // read data to search

                    k = Lint.binsearch(x);

                    if(k??? //complete it

          }

          inf.close();

} catch (Exception e) {prt("Exception " + e + "\n");}

}// end main method      

//   listarr.java

// Array implementation of list in JAVA
import java.util.*;
//*************** Class Definition *********************************
/**
* Implementation of the ADT List using a fixed-length array.
* Exception is thrown:
* if insert operation is attempted when List is full.
* if delete operation is attempted when List is empty.
* if position of insert or delete is out of range.
*/
   public class listarr implements list{
       // class Variables
       protected int capacity, last;
       protected T arr[];   

       listarr(int n){ // List Constructor
           last = 0;
           capacity = n;
           //Allocate Space            
          arr = (T[]) new Object[n+1];
          prt("\n List size = " + n);
       }

        public boolean isEmpty(){return (last == 0);}
        public int   length(){return last;}
       public boolean isFull() {return (last == capacity);}
       public static void prt(String s){System.out.print(s);}

       // insert x at position p (valid p's 1 <= p <= last+1 && last != capacity)      
       public void insert(T x, int p) throws invalidinsertion {
           prt("\nInsert " + x + " at position " + p);
       if (isFull() || p < 1 || p > last + 1)throw new invalidinsertion(p);
           // Shift from position p to right
           for (int i = last ; i >= p ; i--) arr[i+1] = arr[i];
           arr[p] = x; last++;
       }

       // delete element at position p (1...last)      
       public void delete(int p)throws invaliddeletion {
           prt("\nDelete " + p + "th element, ");
           if ( isEmpty() || p < 1 || p > last) throw new invaliddeletion(p);
           // Shift from position p + 1 to left
           for (int i = p ; i < last ; i++) arr[i] = arr[i+1];
           last --;
       }

       public String toString() {
           String s = "[";
       for (int i = 1; i <= last; i++) s += ", " + arr[i] ;
return s + "]";
        }       

       public static void main(String args[]) {
           int j, p, n, x, MaxNum = 5;
           Random rand = new Random();

           n = rand.nextInt(MaxNum) + 1;   // generate n randomly      

           // Create a List of type Integer of size n
           listarr Lint = new listarr(n);          

           // Generate n element and position randomly and insert in the list
           for(j = 1; j <= n; j++){
               p = rand.nextInt(n); // generate position
               x = rand.nextInt(MaxNum * 4); // generate element

               try {
                   Lint.insert(x,p);
               } catch (Exception e) {prt("Exception " + e + "\n");}
           }          

           prt("\nList: " + Lint.toString() + "\n"); // print list          

           // Delete n element from list randomly and print list
           for(j = 1; j <= n; j++){
               p = rand.nextInt(n); // generate position to delete
               try {
                   Lint.delete(p);
                   prt("\nList: " + Lint.toString() + "\n");
               } catch (Exception e) {prt("Exception " + e + "\n");}
           }

           // Create a List of type String
           n = rand.nextInt(MaxNum) + 1;   // generate n randomly      
           listarr Lstr = new listarr(n);
           try {
               Lstr.insert("Sarah", 1);
               Lstr.insert("Jerry", 1);
               Lstr.insert("Tom", 2);
               } catch (Exception e) {prt("Exception " + e + "\n");}
           prt("\nList: " + Lstr.toString() + "\n");
       }
   }// end class listarr

Solutions

Expert Solution

If you have any doubts, please give me comment...

//   listarr.java

// Array implementation of list in JAVA

import java.util.*;

//*************** Class Definition *********************************

/**

* Implementation of the ADT List using a fixed-length array. Exception is

* thrown: if insert operation is attempted when List is full. if delete

* operation is attempted when List is empty. if position of insert or delete is

* out of range.

*/

public class listarr<T extends Comparable<T>> implements list<T> {

    // class Variables

    protected int capacity, last;

    protected T arr[];

    @SuppressWarnings("unchecked")

    listarr(int n) { // List Constructor

        last = 0;

        capacity = n;

        // Allocate Space

        arr = (T[]) new Comparable[n + 1];

        prt("\n List size = " + n);

    }

    public boolean isEmpty() {

        return (last == 0);

    }

    public int length() {

        return last;

    }

    public boolean isFull() {

        return (last == capacity);

    }

    public static void prt(String s) {

        System.out.print(s);

    }

    // insert x at position p (valid p's 1 <= p <= last+1 && last != capacity)

    public void insert(T x, int p) throws invalidinsertion {

        prt("\nInsert " + x + " at position " + p);

        if (isFull() || p < 1 || p > last + 1)

            throw new invalidinsertion(p);

        // Shift from position p to right

        for (int i = last; i >= p; i--)

            arr[i + 1] = arr[i];

        arr[p] = x;

        last++;

    }

    // delete element at position p (1...last)

    public void delete(int p) throws invaliddeletion {

        prt("\nDelete " + p + "th element, ");

        if (isEmpty() || p < 1 || p > last)

            throw new invaliddeletion(p);

        // Shift from position p + 1 to left

        for (int i = p; i < last; i++)

            arr[i] = arr[i + 1];

        last--;

    }

    public void insertsorted(T x) {

        if (isFull())

            throw new invalidinsertion(0);

        int pos = 0;

        while (pos<last && arr[pos].compareTo(x) < 0) {

            pos++;

        }

        // prt("\nInsert " + x + " at position " + pos);

        // Shift from position p to right

        for (int i = last; i >= pos; i--)

            arr[i + 1] = arr[i];

        arr[pos] = x;

        last++;

    }

    protected int binsearch(T x) {

        int l = 0;

        int r = last - 1;

        while (l <= r) {

            int m = l + (r - l) / 2;

            if (arr[m].equals(x))

                return m;

            if (arr[m].compareTo(x) < 0)

                l = m + 1;

            else

                r = m - 1;

        }

        return -1;

    }

    public String toString() {

        String s = "["+arr[0];

        for (int i = 1; i <= last; i++)

            s += ", " + arr[i];

        return s + "]";

    }

    public static void main(String args[]) {

        int j, n, m, k, x;

        try {

            Scanner inf = new Scanner(System.in);

            n = inf.nextInt();// read No. of data to read

            // Create a List of type Integer of size n

            listarr<Integer> Lint = new listarr<Integer>(n);

            // Read n element and insert in a sorted listposition randomly in the list

            for (j = 1; j <= n; j++) {

                x = inf.nextInt(); // read element

                Lint.insertsorted(x);

            }

            System.out.printf("\nThe %d inserted data are as follow:", n);

            System.out.print(Lint.toString());

            // read No. of data to search

            m = inf.nextInt();

            for (j = 1; j <= m; j++) {

                x = inf.nextInt(); // read data to search

                k = Lint.binsearch(x);

                if (k != -1)

                    System.out.print("\n"+x + ": is found!");

                else

                    System.out.print("\n"+x + ": Ooops is not in the list?");

            }

            inf.close();

        } catch (Exception e) {

            prt("Exception " + e + "\n");

        }

    }// end main method

}// end class listarr


Related Solutions

~IMPORTANT: you are NOT allowed to modify public static void main.~ Complete and fix program, by...
~IMPORTANT: you are NOT allowed to modify public static void main.~ Complete and fix program, by defining a countOccurrences function, and by modifying the existing mostFrequentCharacter function, so as to satisfy the following specs: Function countOccurrences takes two arguments, a string and a character. It returns the number of times the character occurs in the string. Function mostFrequentCharacter takes a string as an argument. It returns the character that occurs the most times in the string. If multiple characters tie...
Task 2/2: Java program Based upon the following code: public class Main {   public static void...
Task 2/2: Java program Based upon the following code: public class Main {   public static void main( String[] args ) {     String alphabet = "ABCDEFGHIJKLMNMLKJIHGFEDCBA";     for( <TODO> ; <TODO> ; <TODO> ) {       <TODO>;     } // Closing for loop   } // Closing main() } // Closing class main() Write an appropriate loop definition and in-loop behavior to determine if the alphabet string is a palindrome or not. A palindrome is defined as a string (or more generally, a token) which...
Modify StudentLinkedList class by adding the following methods: printStudentList: print by calling and printing “toString” of...
Modify StudentLinkedList class by adding the following methods: printStudentList: print by calling and printing “toString” of every object in the linkedList. Every student object to be printed in a separate line.  deleteStudentByID(long id): delete student object from the list whose ID is matching with the passed parameter.  sortListByID(): sort the linkedlist according to students IDs.  findMarksAverage(): find the average of all marks for all students in the list.  findMinMark(int markIndex): find the student with the minimum...
Problem 3: Modify StudentLinkedList class by adding the following methods:  printStudentList: print by calling and...
Problem 3: Modify StudentLinkedList class by adding the following methods:  printStudentList: print by calling and printing “toString” of every object in the linkedList. Every student object to be printed in a separate line.  deleteStudentByID(long id): delete student object from the list whose ID is matching with the passed parameter.  sortListByID(): sort the linkedlist according to students IDs.  findMarksAverage(): find the average of all marks for all students in the list.  findMinMark(int markIndex): find the student...
JAVA- Modify the LinkedList1 class presented in this chapter by adding sort() and reverse() methods. The...
JAVA- Modify the LinkedList1 class presented in this chapter by adding sort() and reverse() methods. The reverse method reverses the order of the elements in the list, and the sort method rearranges the elements in the list so they are sorted in alphabetical order. The class should use recursion to implement the sort and reverse operations. Extend the graphical interface in the LinkedList1Demo class to support sort and reverse commands, and use it to test the new methods. LinkedList1: class...
Consider the following interface: public interface Car{ public String getMake(); public void setMake(); public void honk();...
Consider the following interface: public interface Car{ public String getMake(); public void setMake(); public void honk(); public void crash(); public void drive(); } public interface Boat{ public String getMake (); public void setMake (); public void blast_horn(); public void sink(); public void move(); } 1. Create a concrete FamilyCar class from the Car interface.
please modify the method public void addList(SinglyLinkedList<E> s) that add list to another with addlast() and...
please modify the method public void addList(SinglyLinkedList<E> s) that add list to another with addlast() and remove() methods without changing the parameter of addList method. ////////////////////////////////////////////////// public class SinglyLinkedList<E> {      private class Node<E> {            private E element;            private Node<E> next;            public Node(E e, Node<E> n) {                 element = e;                 next = n;            }            public E getElement() {                 return element;            }            public void setElement(E element) {                 this.element = element;...
1. Consider the following code: public class Widget implements Serializable { private int x; public void...
1. Consider the following code: public class Widget implements Serializable { private int x; public void setX( int d ) { x = d; } public int getX() { return x; } writeObject( Object o ) { o.writeInt(x); } } Which of the following statements is true? I. The Widget class is not serializable because no constructor is defined. II. The Widget class is not serializable because the implementation of writeObject() is not needed. III. The code will not compile...
Consider this program: public class Main { public static void main(String[] args) { String s1 =...
Consider this program: public class Main { public static void main(String[] args) { String s1 = "hello"; String s2 = "hello"; String s3 = new String("hello"); System.out.println(s1 == s2); System.out.println(s2 == s3); System.out.println(s2.equals(s3)); } } When we run the program, the output is: true false true Explain why this is the output, using words and/or pictures.
write program that develop a Java class Dictionary to support the following public methods of an...
write program that develop a Java class Dictionary to support the following public methods of an abstract data type: public class Dictionary { // insert a (key, value) pair into the Dictionary, key value must be unique, the value is associated with the key; only the last value inserted for a key will be kept public void insert(String key, String value); // return the value associated with the key value public String lookup(String key); // delete the (key, value) pair...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT