Question

Java Program Create a class to store an array of with enough space to store 10 integer values. Us...

Java Program

Create a class to store an array of with enough space to store 10 integer values.

Using the principle of recursion, implement the following:

*getSize : returns the size of the array.

*get (i): returns the i-th element of the array. If the element does not exist, it throws a "NoSuchElementException” which is a subclass of Java class RunTimeException.

*add (val): inserts value as the last element of the array. If necessary, double the size of the current array to accommodate the new item.

*equals: Two MyArrays are equal if they have the same number of elements in the same order. Implement this overriding method recursively.

*sum: returns the sum of all elements of the array. Implement this recursively.

*max: returns the largest element of the array.  Implement this recursively.

*min: returns the smallest element of the array. . Implement this recursively.

*srch (elt): Searches for the element using the recursive binary search algorithm and returns the index of position where it is found, -1 if not found.

*sort: Sorts the array using the bubble sort algorithm.  Implement this recursively.

*invert: Inverts the order of elements in the array.  Implement this recursively

*toString: This must return a String which contains complete information about the array including how many elements it has and what are their values. Overrides the same method in the Object class.

To test the program, follow the instructions below:

Please use JOptionPane,  FileReader to read form a text input file and PrintWriterwrite to write to the output file

*Create a default MyArray MA1.

*Prompt the user for the name of the input and output files.

*Output the size of MA1.

*Read the number of elements to insert in MA1. Let this be n. [This is the first line of input from the file.]

*Now, read n integer values from the file and insert them in MA1 in that order.

*Output the size of MA1.

*Output MA1.

*Find and output the largest and smallest elements of MA1.

*Output the sum of all elements of MA1.

*Create another MyArray MA2 by copying MA1.

*Check and output if MA1 and MA2 are equal.

*Sort MA2 using the recursive bubble sort algorithm.

*Check and output if MA1 and MA2 are equal.

*Output MA2.

*Read the search elements from the input file (just continue to read the input file) till the end of the file, and for each element, output if that element exists in MA2. If it does, output its position; otherwise indicate that it does not exist in the array.

*Invert MA2.

*output MA2.

Input File:

13 // Number of elements to insert in the array

573

2739

76321

3873

73430

333

7293

38383

272

946

3832

8410

2583 // Last element for insertion - Search Elements follow

333

946

76321

26353

833

3832

123

573

765

2583

0 0
Add a comment Improve this question Transcribed image text
Answer #1
/**
 * @fileName MyArray.java
 * @author 
 * @since 14/3/17
 */


package myarray;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class MyArray {
    private int arr[];
    private int size;


    /**
     * This is default constructor
     */
    public MyArray() {
        arr = new int[10];
    }

    /**
     * This parametrized constructor
     *
     * @param size
     */
    public MyArray(int size) {
        arr = new int[size];
    }

    /**
     * This is copy constructor
     *
     * @param myArray
     */
    public MyArray(MyArray myArray) {
        this.arr = myArray.arr;
        this.size = myArray.size;
    }


    public static void main(String[] args) throws FileNotFoundException {
        MyArray MA1 = new MyArray();
        Scanner sc = new Scanner(System.in);
        System.out.print("enter the name of input file:");
        String inputFileName = sc.nextLine();
        System.out.print("enter the name of input file:");
        String outputFileName = sc.nextLine();

        sc.close();
        System.out.println(MA1.getSize());

        sc = new Scanner(new FileReader(inputFileName));
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            MA1.add(sc.nextInt());
        }


        System.out.println("Size of MA1:" + MA1.getSize());
        System.out.println("MA1:" + MA1);
        System.out.println("MAX:" + MA1.max());
        System.out.println("MIN:" + MA1.min());
        System.out.println("SUM:" + MA1.sum());


        MyArray MA2 = new MyArray(MA1);
        System.out.println(MA1.equals(MA2));
        System.out.println(MA2);
        MA2.recursiveBubbleSort();
        System.out.println(MA1.equals(MA2));
        while (sc.hasNext()) {
            int elem = sc.nextInt();
            int a = MA2.binarySearch(elem);
            if (a != -1) {
                System.out.println(a);
            } else {
                System.out.println(elem + " does not exist in array");
            }
        }

        MA2.reverse();
        System.out.println(MA2);


    }


    /**
     * This method return the count of element
     *
     * @return
     */
    public int getSize() {
        return this.size;
    }

    /**
     * This method return the value at given index, index start from 0
     *
     * @param index
     * @return
     */
    public int get(int index) {
        if (index >= size) {
            throw new NoSuchElementException();
        } else {
            return this.arr[index];
        }
    }

    /**
     * This method will add the given value at the end of array
     *
     * @param val
     */
    public void add(int val) {
        if (size >= this.arr.length) {
            int[] arr = new int[this.arr.length * 2];
            for (int i = 0; i < this.arr.length; i++) {
                arr[i] = this.arr[i];
            }
            this.arr = arr;
            this.arr[size] = val;
        } else {
            this.arr[size] = val;
        }
        size++;

    }

    public int max() {
        return max(0);
    }

    public int max(int index) {
        if (index != size) {
            return Math.max(this.arr[index], max(index + 1));
        } else {
            return this.arr[0];
        }
    }

    public int min() {
        return min(0);
    }

    public int min(int index) {
        if (index != size) {
            return Math.min(this.arr[index], min(index + 1));
        } else {
            return this.arr[0];
        }
    }

    public int sum() {
        return sum(0);
    }

    private int sum(int index) {
        if (index == size) {
            return this.arr[index - 1];
        } else {
            return this.arr[index] + sum(index + 1);
        }
    }


    public int binarySearch(int target) {
        return binarySearch(this.arr, 0, size - 1, target);
    }

    public int binarySearch(int[] a, int start, int end, int target) {
        int middle = (start + end) / 2;
        if (end < start) {
            return -1;
        }

        if (target == a[middle]) {
            return middle;
        } else if (target < a[middle]) {
            return binarySearch(a, start, middle - 1, target);
        } else {
            return binarySearch(a, middle + 1, end, target);
        }
    }


    public int[] recursiveBubbleSort() {
        return recursiveBubbleSort(size);
    }

    public int[] recursiveBubbleSort(int n) {
        if (n == 1) {
            return this.arr; //finished sorting
        }

        int temp;
        for (int i = 0; i < n - 1; i++) {
            if (this.arr[i + 1] < this.arr[i]) {
                temp = this.arr[i];
                this.arr[i] = this.arr[i + 1];
                this.arr[i + 1] = temp;
            }
        }
        return recursiveBubbleSort(n - 1);
    }


    public void reverse() {
        reverse(0, size - 1);
    }

    public void reverse(int start, int end) {
        if (start < end) {
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            reverse(start + 1, end - 1);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MyArray myArray = (MyArray) o;

        if (size != myArray.size) return false;
        return Arrays.equals(arr, myArray.arr);
    }

    @Override
    public int hashCode() {
        int result = Arrays.hashCode(arr);
        result = 31 * result + size;
        return result;
    }


    @Override
    public String toString() {
        String s = "Size:" + size + " Elements: ";
        for (int i = 0; i < size; i++) {
            s += arr[i] + " ";
        }
        return s;

    }
}

output:

enter the name of input file:inputint.txt enter the name of input file:output. txt 03 Size of MA1: 13 MA1:Size:13 Elements: 5

Add a comment
Know the answer?
Add Answer to:
Java Program Create a class to store an array of with enough space to store 10 integer values. Us...
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
  • In Java, Implement a class MyArray as defined below, to store an array of integers (int)....

    In Java, Implement a class MyArray as defined below, to store an array of integers (int). Many of its methods will be implemented using the principle of recursion. Users can create an object by default, in which case, the array should contain enough space to store 10 integer values. Obviously, the user can specify the size of the array s/he requires. Users may choose the third way of creating an object of type MyArray by making a copy of another...

  • In C only Please! This lab is to write a program that will sort an array...

    In C only Please! This lab is to write a program that will sort an array of structs. Use the functions.h header file with your program. Create a source file named functions.c with the following: A sorting function named sortArray. It takes an array of MyStruct's and the length of that array. It returns nothing. You can use any of the sorting algorithms, you would like though it is recommended that you use bubble sort, insertion sort, or selection sort...

  • Copy the following java codes and compile //// HighArray.java //// HighArrayApp.java Study carefully the design and...

    Copy the following java codes and compile //// HighArray.java //// HighArrayApp.java Study carefully the design and implementation HighArray class and note the attributes and its methods.    Create findAll method which uses linear search algorithm to return all number of occurrences of specified element. /** * find an element from array and returns all number of occurrences of the specified element, returns 0 if the element does not exit. * * @param foundElement   Element to be found */ int findAll(int...

  • JAVA - Natural Quick Sort .txt and Return ----------------------------------------------------------------------------- The program should input a .txt file...

    JAVA - Natural Quick Sort .txt and Return ----------------------------------------------------------------------------- The program should input a .txt file like below and must use a Quick sort Algorithm ================ 6 10 4 19 10 12 8 6 0 1 2 3 ================ The first number "6" represents the index of the element to return after sort the second number on the top "10" represents the number of elements or size of array. The following numbers and lines are the elements that need to...

  • The name of the C++ file must be search.cpp Write a program that will read data...

    The name of the C++ file must be search.cpp Write a program that will read data from a file. The program will allow the user to specify the filename. Use a loop that will check if the file is opened correctly, otherwise display an error message and allow the user to re-enter a filename until successful. Read the values from the file and store into an integer array. The program should then prompt the user for an integer which will...

  • Write a java program: Create a method fillRandom() that accepts an array of int as input...

    Write a java program: Create a method fillRandom() that accepts an array of int as input and populates it with random numbers in the range -999 to 1000 Explicitly store zero in index [0] and 900 in index [1]. (0 and 900 will be used as search keys) Create a method DisplayLastInts() that accepts an array of int as input and displays the last hundred elements to the screen in rows of 10 elements. Format the output so the 10...

  • A method called linearSearch(), which takes as parameters an array of int followed by three values...

    A method called linearSearch(), which takes as parameters an array of int followed by three values of type int, and returns a value of type int. The first int parameter represents a key, the second int parameter represents a starting position, and the third int parameter represents an end position. If the key occurs in the array between the start position (inclusive) and the end position (exclusive), the method returns the position of the first occurrence of the key in...

  • Program in C++! Thank you in advance! Write a menu based program implementing the following functions: (1) Write a funct...

    Program in C++! Thank you in advance! Write a menu based program implementing the following functions: (1) Write a function that prompts the user for the name of a file to output as a text file that will hold a two dimensional array of the long double data type. Have the user specify the number of rows and the number of columns for the two dimensional array. Have the user enter the values for each row and column element in...

  • Make a program using Java that asks the user to input an integer "size". That integer...

    Make a program using Java that asks the user to input an integer "size". That integer makes and prints out an evenly spaced, size by size 2D array (ex: 7 should make an index of 0-6 for col and rows). The array must be filled with random positive integers less than 100. Then, using recursion, find a "peak" and print out its number and location. (A peak is basically a number that is bigger than all of its "neighbors" (above,...

  • Your goal is to create an ‘Array’ class that is able to hold multiple integer values....

    Your goal is to create an ‘Array’ class that is able to hold multiple integer values. The ‘Array’ class will be given functionality through the use of various overloaded operators You will be given the main() function for your program and must add code in order to achieve the desired result. Do not change any code in main(). If something is not working, you must change your own code, not the code in main(). Assignment 5: overloading member functions. Overview:...

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