Question

In: Computer Science

This needs to be in Java implementing Insertion Sort and displaying the floats sorted. Sample Output:...

This needs to be in Java

implementing Insertion Sort and displaying the floats sorted.

Sample Output: (green is user input)

Please select one of the following:
1: Initialize a default array
2: To specify the max size of the array
3: Add value to the array
4: Display values in the array
5: Display the average of the values
6: Enter multiple values
7: Read values from file
8: Save values to file
9: Sort the array
10: To Exit

import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner;

class Numbers {

      private float[] numbers;

      private int numItems = 0, size = 1;

      public Numbers() {

            numbers = new float[size];// default size }

      public Numbers(int size) {

            this.size = size;

            numbers = new float[size]; }

      public void addValue(Scanner scanner, boolean fromKeyboard) {

            if (fromKeyboard)

                  System.out.print("Enter value: ");

            float value = scanner.nextFloat();

            numbers[numItems++] = value;

            if (numItems >= size) {

                  float[] temp = new float[size + 5];

                  for (int i = 0; i < numItems; i++) {

                        temp[i] = numbers[i];                  }

                  numbers = temp; } }

      public float calcAverage() {

            float sum = 0;

            for (int i = 0; i < numItems; i++) {

                  sum += numbers[i];// calculating sum of the snumbers in the array }

            return (float) sum / numItems;// calculating average }

      @Override

      public String toString() {

            String data = "";

            for (int i = 0; i < numItems; i++) {

                  data += numbers[i] + "\n"; }

            return data; }

      public void addMultiple(Scanner scanner, boolean fromKeyboard) {

            if (fromKeyboard) {

                  System.out.print("How many values do you wish to add? "); }

            int n = scanner.nextInt();

            for (int i = 0; i < n; i++) {

                  addValue(scanner, fromKeyboard);

            } }

      public void loadData(Scanner scanner) {

            System.out.println("Name of the file to read from:");

            String name = scanner.next();

            try {

                  Scanner fileScanner = new Scanner(new File(name));

                  addMultiple(fileScanner, false);

            } catch (FileNotFoundException e) {

                  System.out.println("File not found!");

            } catch (Exception e) {

                  System.out.println("Invalid file format!");

            }

      }

      public void saveData(Scanner scanner) {

            System.out.println("Name of the file to save to:");

            String name = scanner.next();

            try {

                  PrintWriter writer = new PrintWriter(new File(name));

                  writer.println(numItems);

                  for (int i = 0; i < size; i++) {

                        writer.println(numbers[i]);

                  }

                  writer.close();

            } catch (FileNotFoundException e) {

                  System.out.println("File cant be opened!");

            } }}

public class Test {// driver class

      public static void main(String[] args) {

            Numbers obj = new Numbers();

            Scanner sc = new Scanner(System.in);

            while (true) {// infinte loop

                  System.out.print("Please select one of the following:\r\n"

                              + "1: Initialize a default array\r\n"+ "2: To specify the max size of the array\r\n" + "3: Add value to the array\r\n" + "4: Display values in the array\r\n" + "5: Display the average of the values\r\n" + "6: Enter multiple values\r\n" + "7: Read values from file\r\n" + "8: Save values to file\r\n" + "9: To Exit\r\n" + "> ");

                  int choice = sc.nextInt();// taking user choice

                  sc.nextLine();

                  switch (choice) {

                  case 1: System.out.println("New array initialized"); obj = new Numbers(); break;

                  case 2: System.out.print("Enter new size of the array: ");int size = sc.nextInt(); sc.nextLine(); obj = new Numbers(size); break;

                  case 3: obj.addValue(sc, true); break;

                  case 4: System.out.println("Numbers are:\n" + obj); break;

                  case 5: System.out.println("Average is: " + obj.calcAverage()); break;

                  case 6: // adding multiple values from keyboard obj.addMultiple(sc, true);break;

                  case 7:// loading values from fileobj.loadData(sc);break;

                  case 8:// saving values to fileobj.saveData(sc); break;

                  case 9: System.out.println("Good Bye"); System.exit(0);// exiting the program

                  default: System.out.println("Invalid choice!"); break;  } } }}

Solutions

Expert Solution

If you have any problem with the code feel free to comment. I have highlighted the changes in the code

Program

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

class Numbers {

   private float[] numbers;

   private int numItems = 0, size = 1;

   public Numbers() {

       numbers = new float[size];// default size
   }

   public Numbers(int size) {

       this.size = size;

       numbers = new float[size];
   }

   public void addValue(Scanner scanner, boolean fromKeyboard) {

       if (fromKeyboard)

           System.out.print("Enter value: ");

       float value = scanner.nextFloat();

       numbers[numItems++] = value;
       validateArraySize();
   }

   public void validateArraySize() {
       if (numItems >= size) {

           float[] temp = new float[size + 5];

           for (int i = 0; i < numItems; i++) {

               temp[i] = numbers[i];
           }

           numbers = temp;
       }
   }

   public float calcAverage() {

       float sum = 0;

       for (int i = 0; i < numItems; i++)

           sum += numbers[i];// calculating sum of the snumbers in the array }

       return (float) sum / numItems; // calculating average }
   }

   @Override
   public String toString() {

       String data = "";

       for (int i = 0; i < numItems; i++) {

           data += numbers[i] + "\n";
       }

       return data;
   }

   public void addMultiple(Scanner scanner, boolean fromKeyboard) {

       if (fromKeyboard) {

           System.out.print("How many values do you wish to add? ");
       }

       int n = scanner.nextInt();

       for (int i = 0; i < n; i++) {

           addValue(scanner, fromKeyboard);

       }
   }

   public void loadData(Scanner scanner) {

       System.out.println("Name of the file to read from:");

       String name = scanner.nextLine();

       try {

           Scanner fileScanner = new Scanner(new File(name));

           while (fileScanner.hasNext()) {
               float value = Float.parseFloat(fileScanner.nextLine());
               numbers[numItems++] = value;
               validateArraySize();
           }
           fileScanner.close();

       } catch (FileNotFoundException e) {

           System.out.println("File not found!");

       } catch (Exception e) {

           System.out.println("Invalid file format!");

       }

   }

   public void saveData(Scanner scanner) {

       System.out.println("Name of the file to save to:");

       String name = scanner.next();

       try {

           PrintWriter writer = new PrintWriter(new File(name));

           writer.println(numItems);

           for (int i = 0; i < size; i++) {

               writer.println(numbers[i]);

           }

           writer.close();

       } catch (FileNotFoundException e) {

           System.out.println("File cant be opened!");

       }
   }

   public void sortArray() {
       //performing insertion sort
       for (int i = 1; i < numItems; ++i) {
           float toInsert = numbers[i];
           int j = i - 1;
           while (j >= 0 && numbers[j] > toInsert) {
               numbers[j + 1] = numbers[j];
               j = j - 1;
           }
           numbers[j + 1] = toInsert;
       }
   }

}

public class Test {// driver class

   public static void main(String[] args) {

       Numbers obj = new Numbers();

       Scanner sc = new Scanner(System.in);

       while (true) {// infinte loop

           System.out.print("Please select one of the following:\r\n"

                   + "1: Initialize a default array\r\n" + "2: To specify the max size of the array\r\n"
                   + "3: Add value to the array\r\n" + "4: Display values in the array\r\n"
                   + "5: Display the average of the values\r\n" + "6: Enter multiple values\r\n"
                   + "7: Read values from file\r\n" + "8: Save values to file\r\n" + "9: Sort the array\r\n"
                   + "10: To Exit\r\n" + "> ");

           int choice = sc.nextInt();// taking user choice

           sc.nextLine();

           switch (choice) {

           case 1:
               System.out.println("New array initialized");
               obj = new Numbers();
               break;

           case 2:
               System.out.print("Enter new size of the array: ");
               int size = sc.nextInt();
               sc.nextLine();
               obj = new Numbers(size);
               break;

           case 3:
               obj.addValue(sc, true);
               break;

           case 4:
               System.out.println("Numbers are:\n" + obj);
               break;

           case 5:
               System.out.println("Average is: " + obj.calcAverage());
               break;

           case 6:
               obj.addMultiple(sc, true);
               break;

           case 7:
               obj.loadData(sc);
               break;

           case 8:
               obj.saveData(sc);
               break;

           case 9:
               obj.sortArray();
               break;

           case 10:
               System.out.println("Good Bye");
               System.exit(0);// exiting the program

           default:
               System.out.println("Invalid choice!");
               break;
           }
       }
   }
}

Output

Input


Related Solutions

This is an exercise in correctly implementing insertion sort and selection sort. This assignment includes a...
This is an exercise in correctly implementing insertion sort and selection sort. This assignment includes a text data file containing information on tutorial websites for a variety of programming languages. The data file is named Tutorials. It contains records of programming tutorial websites. The record structure for this text file is: FIELD 1 = Programming Language FIELD 2 = Name and Description of Website FIELD 3 = URL Web Address of Language Tutorial The structure of the file is that...
Implement Library Sort in Java which is a version of Insertion Sort with gaps to speed...
Implement Library Sort in Java which is a version of Insertion Sort with gaps to speed up the computation. If the pseudocode in Wikipedia (https://en.wikipedia.org/wiki/Library_sort) is not enough, you can download the research paper from (https://arxiv. org/pdf/cs/0407003.pdf). Below is the algorithm and pseudo code. Implementation Algorithm Let us say we have an array of n elements. We choose the gap we intend to give. Then we would have a final array of size (1 + ε)n. The algorithm works in...
Write a program in Java to sort the given array using merge sort, quick sort, insertion...
Write a program in Java to sort the given array using merge sort, quick sort, insertion sort, selection sort and bubble sort based on the input from the user which sorting technique they wanted to use. Get the array size, array elements from the user, and also display the sorted array along with the name of the sorting technique used.
The insertion sort algorithm updates its sorted array as each new data value is entered. It...
The insertion sort algorithm updates its sorted array as each new data value is entered. It is an in-place algorithm, in that the sorted array at each step writes over the array from the previous step. • Let us start with sorting in descending order (largest to smallest). The ascending order case follows as a simple modification to the descending case. • Assume that we have thus far read N values and these are sorted in correct order (largest to...
write a java merge sort called MERGE-SORT-A(), Using recursive calls and NO INSERTION-SORT() as a sub-procedure.
write a java merge sort called MERGE-SORT-A(), Using recursive calls and NO INSERTION-SORT() as a sub-procedure.
Run Solver.java, where 20 array instances of 1M random integers are sorted (using Insertion- sort and...
Run Solver.java, where 20 array instances of 1M random integers are sorted (using Insertion- sort and Heap-sort, respectively). Solver.java is given, however the two sorting algorithms of course are implemented by yourself. Report the time elapsed running Solver.java, using Insertion-sort, and Heap-sort, respectively. Based on your results, comment comparatively on time-efficiency of the two sorting algorithms ////// public class Solver {    public static void main(String[] args) { final int SIZE = 1000000; // 1 million final int Instances=20; int[][]...
develop the Binary search with swap count: Use sorted data from insertion sort (part A) Permutations,...
develop the Binary search with swap count: Use sorted data from insertion sort (part A) Permutations, Insertion Sort – implement algorithms Permutations (Johnson Trotter): {1, 2, 3, 4, 5}; Insertion Sort: {45, 24, 16, 92, 71, 69, 28} develop count of # data “insertions” and develop # of key compares against the following: 16, 77, 24, 92, 44
Insertion sort for 12, 2, 3, 21, 11, 10,8 java lanuage
Insertion sort for 12, 2, 3, 21, 11, 10,8 java lanuage
All code in JAVA please 1. Implement Insertion Sort 2. Implement Selection Sort *For problem 1...
All code in JAVA please 1. Implement Insertion Sort 2. Implement Selection Sort *For problem 1 and 2, please: a. Let the program generate a random array. b. Output both the original random array and the sorted version of it
Can someone implement the following in Java? Quicksort with switching to Insertion sort when the number...
Can someone implement the following in Java? Quicksort with switching to Insertion sort when the number of elements in the subarray is less than or equal to 2% of the original number Requirements: 1) functions from standard libraries implementing Quicksort are NOT allowed;
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT