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...
Using Java create a program that does the following: Modify the LinkedList1 class by adding sort()...
Using Java create a program that does the following: Modify the LinkedList1 class 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. Do not use recursion to implement either of these operations. Extend the graphical interface in the LinkedList1Demo class to support sort and reverse commands, and use it to test the new methods....
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...
Given a program as shown below: #include <stdio.h> void function1(void); void function2 (int, double x); void...
Given a program as shown below: #include <stdio.h> void function1(void); void function2 (int, double x); void main (void) { int m; double y; m=15; y=308.24; printf ("The value of m in main is m=%d\n\n",m); function1(); function2(m,y); printf ("The value of m is main still m = %d\n",m); } void function1(void) { printf("function1 is a void function that does not receive\n\\r values from main.\n\n"); } void function2(int n, double x) { int k,m; double z; k=2*n+2; m=5*n+37; z=4.0*x-58.4; printf ("function2 is...
Given a program as shown below: #include <stdio.h> void function1(void); void function2 (int, double x); void...
Given a program as shown below: #include <stdio.h> void function1(void); void function2 (int, double x); void main (void) { int m; double y; m=15; y=308.24; printf ("The value of m in main is m=%d\n\n",m); function1(); function2(m,y); printf ("The value of m is main still m = %d\n",m); } void function1(void) { printf("function1 is a void function that does not receive\n\\r values from main.\n\n"); } void function2(int n, double x) { int k,m; double z; k=2*n+2; m=5*n+37; z=4.0*x-58.4; printf ("function2 is...
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.
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT