Question

In: Computer Science

Objectives In this lab you will review passing arrays to methods and partially filled arrays. Requirements...

Objectives In this lab you will review passing arrays to methods and partially filled arrays. Requirements 1. Fill an array with data from an input file sampledata-io.txt (Attached) a. Assume no more than 100 data items, terminated by -1 for sentinel b. Note that the sample data file has other information after the sentinel; it should cause no problem c. Read and store data d. Print the number of data stored in the array e. Add a method to reverse the array. Pass the original array as the argument and return the reversed array. 2. Testing a. Invoke the reverse method, print out the reversed array. 3. Inserting into the partially filled array a. Add a method to insert a user inputted value into a specific location. b. Remember to check parameters for validity. Also remember to check whether the array is full or not. c. Invoke the insert method, prompt to user whether the insertion is successful or not. 4. Removing from the partially filled array a. Add a method to remove the element at the specific location in the partially filled array. b. Invoke the remove method, prompt to user whether the remove is successful or not. If the remove is successful, print out the value of the element just removed. There are several important points that are general requirements for labs in this course: ♣ Include a comment at the beginning of each source file you submit that includes your name and the lab date. ♣ Names for variables and other program components should be chosen to help convey the meaning of the variable. ♣ Turn in an archive of the entire Eclipse project for each lab. Do not attempt to turn in individual files, some course management systems mangle such files.

Solutions

Expert Solution

package myProject;
import java.util.*;
import java.io.File;
//Create a class Array Operation
public class ArrayOperation
{
   //Initializes the counter to zero
   int counter = 0;

   //Method to read data from file
   void readData(int numberArray[])
   {
       //File object created
       File file = new File("D:/TODAY/src/myProject/data.txt");
      
       //Handles exception      
       try
       {
           //Scanner object created
           Scanner scanner = new Scanner(file);
           //Checks for the data availability
           while(scanner.hasNextInt())
           {
               //Reads a number from the file
               int no = scanner.nextInt();
               //Checks if the number is -1 then stop reading
               if(no == -1)
                   break;
               //Stores the number in the array
           numberArray[counter++] = no;
           }//End of while
       }//End of try

       //Catch block
       catch(Exception e)
       {
           e.printStackTrace();
       }//End of catch

       //Displays number of elements present in the array
       System.out.println("Numbers of data stored in array = " + counter);
   }//End of method
  
   //Method to display the array in reverse order
   void displayReverse(int numberArray[])
   {
       System.out.println("Numbers in reverse order: ");

       //Loops from end to beginning and displays the elements in reverse order
       for(int i = counter - 1; i >= 0 ; i--)
               System.out.print(numberArray[i] + " ");
   }
  
   //Displays the contents of the array
   void displayArray(int numberArray[])
   {
       //Loops from beginning to end and displays the array contents
       for(int c = 0; c < counter; c++)
           System.out.print(numberArray[c] + " ");
   }
  
   //Returns the status of insertion operation
   boolean insertSpecifiedLocation(int numberArray[])
   {
       //Initializes the status to false
       boolean status = false;

       //Loop variable
       int c;
      
       //Scanner class object created
       Scanner scanner = new Scanner(System.in);
      
       //Accepts the position and number for insertion
       System.out.println("\nEnter the poistion to insert a number: ");
       int position = scanner.nextInt();
       System.out.println("Enter the a number to insert at position: " + position);
       int number = scanner.nextInt();

       //Checks the validity of the position
       if(position >= 0 && position < counter)
       {
           //Checks the overflow condition
           if(counter > 99)
               System.out.println("Error: Overflow Memory, Array is full");
          
           else
           {
               //Loops from end of the array to the position specified.
               //position - 1 because array index position starts from 0
               for(c = counter - 1; c >= position - 1; c--)
                   //Shifting the values to next position till the position specified
                   numberArray[c + 1] = numberArray[c];
              
               //Stores the number in the specified position. position - 1 because array index position starts from 0
               numberArray[position - 1] = number;
              
               //Increase the length of the array by 1
               counter++;
              
               //Update the status to true for successful insertion
               status = true;
           }//end of else
       }//End of if
       //Displays error message
       else
           System.out.println("Error: Invalid Position");
      
       //Returns the status
       return status;
   }//End of method
  
   //Method removes a number from a specified position and returns the status
   boolean removeSpecifiedLocation(int numberArray[])
   {
       //Initializes the status to false
       boolean status = false;
      
       //Loop variable
       int c;
      
       //scanner class object created
       Scanner scanner = new Scanner(System.in);
      
       //Accept the position to remove the number
       System.out.println("\nEnter the poistion to remove a number: ");
       int position = scanner.nextInt();
      
       //Checks the validity of the position
       if(position >= 0 && position < counter)
       {
           //If the length is zero no more element to be deleted
           if(counter == -1)
               System.out.println("Error: Underflow Memory, Array is empty");
           else
           {
               //Displays the removed element
               System.out.println("Removed element: " + numberArray[position - 1]);
              
               //Loops from the specified position to the length of the array.
               //position - 1 because array index position starts from 0
               for(c = position - 1; c < counter; c++)
                   //Shifting the next position value to the current position till the position specified
                   numberArray[c] = numberArray[c + 1];
              
               //Decrease the length by 1
               counter--;

               //Update the status to true for successful deletion
               status = true;
           }//End of else
       }//End of if

       //Displays error message
       else
           System.out.println("Error: Invalid Position");
      
       //Returns the status
       return status;
   }//End of method
  
   //Method to display menu
   void menu()
   {
       System.out.println("\n1) Display Reverse order");
       System.out.println("2) Insert a number into a specified position");
       System.out.println("3) Remove a number from specified position");
       System.out.println("4) Exit");
   }
  
   //Main method to test
   public static void main(String ss[])
   {
       //Creates an array of size 100
       int numberArray [] = new int[100];
      
       //status to check success of failure
       boolean status;
      
       //To store user choice
       int ch;
      
       //Scanner class object created
       Scanner scanner = new Scanner(System.in);
      
       //Creates ArrayOperation class object
       ArrayOperation ao = new ArrayOperation();
      
       //Call readData to read data from file
       ao.readData(numberArray);
      
       //Loops till user choice
       do
       {
           //Calls menu method to display menu
           ao.menu();

           //Accepts user choice
           System.out.println("\n Enter your choice: ");
           ch = scanner.nextInt();
          
           switch(ch)
           {
               //To display in reverse order
               case 1:
                   ao.displayReverse(numberArray);
                   break;
                  
               //To insert a number at specified position
               case 2:
                   status = ao.insertSpecifiedLocation(numberArray);

                   //If the status is true Display the array
                   if(status)
                   {
                       System.out.println("Insertion successfull \n After Insertion: ");
                       ao.displayArray(numberArray);      
                   }
                   break;

               //To Remove an element
               case 3:
                   status = ao.removeSpecifiedLocation(numberArray);
                   //If the status is true Display the array
                   if(status)
                   {
                       System.out.println("Deletion successfull \n After Deletion: ");
                       ao.displayArray(numberArray);
                   }
                   break;

               //Exit the program
               case 4:
                   System.out.println("Thank You");
                   System.exit(0);                  
               default:
                   System.out.println("Invalid Choice");
           }   //End of switch
       }while(true);      
   }//End of main method  
}//End of class

Output:

Numbers of data stored in array = 8

1) Display Reverse order
2) Insert a number into a specified position
3) Remove a number from specified position
4) Exit

Enter your choice:
1
Numbers in reverse order:
66 45 56 80 50 30 20 10
1) Display Reverse order
2) Insert a number into a specified position
3) Remove a number from specified position
4) Exit

Enter your choice:
2

Enter the poistion to insert a number:
12
Enter the a number to insert at position: 12
66
Error: Invalid Position

1) Display Reverse order
2) Insert a number into a specified position
3) Remove a number from specified position
4) Exit

Enter your choice:
2

Enter the poistion to insert a number:
3
Enter the a number to insert at position: 3
88
Insertion successfull
After Insertion:
10 20 88 30 50 80 56 45 66
1) Display Reverse order
2) Insert a number into a specified position
3) Remove a number from specified position
4) Exit

Enter your choice:
3

Enter the poistion to remove a number:
56
Error: Invalid Position

1) Display Reverse order
2) Insert a number into a specified position
3) Remove a number from specified position
4) Exit

Enter your choice:
3

Enter the poistion to remove a number:
1
Removed element: 10
Deletion successfull
After Deletion:
20 88 30 50 80 56 45 66
1) Display Reverse order
2) Insert a number into a specified position
3) Remove a number from specified position
4) Exit

Enter your choice:
3

Enter the poistion to remove a number:
4
Removed element: 50
Deletion successfull
After Deletion:
20 88 30 80 56 45 66
1) Display Reverse order
2) Insert a number into a specified position
3) Remove a number from specified position
4) Exit

Enter your choice:
4
Thank You


Related Solutions

Objectives: 1. using indirect addressing 2. passing parameters 3. generating “random” numbers 4. working with arrays...
Objectives: 1. using indirect addressing 2. passing parameters 3. generating “random” numbers 4. working with arrays Description: Write and test a MASM (assembly language) program to perform the following tasks: 1. Introduce the program. 2. Get a user request in the range [min = 10 .. max = 200]. 3. Generate request random integers in the range [lo = 100 .. hi = 999], storing them in consecutive elements of an array. 4. Display the list of integers before sorting,...
) Use functions and arrays to complete the following programs. Requirements: • You should use the...
) Use functions and arrays to complete the following programs. Requirements: • You should use the divide-and-conquer strategy and write multiple functions. • You should always use arrays for the data sequences. • You should always use const int to define the sizes of your arrays. a. Write a C++ program. The program first asks the user to enter 4 numbers to form Sequence 1. Then the program asks the user to enter 8 numbers to form Sequence 2. Finally,...
Summary In this lab, you add the input and output statements to a partially completed Java...
Summary In this lab, you add the input and output statements to a partially completed Java program. When completed, the user should be able to enter a year, a month, and a day to determine if the date is valid. Valid years are those that are greater than 0, valid months include the values 1 through 12, and valid days include the values 1 through 31. Instructions Notice that variables have been declared for you. Write the simulated housekeeping() method...
You MUST use VECTORS in this lab. Do NOT use ARRAYS. Write code in C++ with...
You MUST use VECTORS in this lab. Do NOT use ARRAYS. Write code in C++ with //comments . Please include a screen shot of the output Part 4: Calorie Counting Specifications: Write a program that allows the user to enter the number of calories consumed per day. Store these calories in an integer vector. The user should be prompted to enter the calories over the course of one week (7 days). Your program should display the total calories consumed over...
You MUST use VECTORS in this lab. Do NOT use ARRAYS. Write code in C++ with...
You MUST use VECTORS in this lab. Do NOT use ARRAYS. Write code in C++ with //comments . Please include a screen shot of the output Part 1: Largest and Smallest Vector Values Specifications: Write a program that generates 10 random integers between 50 and 100 (inclusive) and puts them into a vector. The program should display the largest and smallest values stored in the vector. Create 3 functions in addition to your main function. One function should generate the...
In Lab 4, you made a class with static methods. The static methods converted an integer...
In Lab 4, you made a class with static methods. The static methods converted an integer in binary, Hex, and Octal. To do this, you made a class of static methods. The class did not have any fields. The static methods received the integer value as a parameter. For this lab, make all of the static methods, non-static methods. Lab 5 Requirements Create a class named “Lab5_IntConv_Class Have one private field name intValue. Add two constructors: One is a default...
You have been hired to undertake a review of the corporate governance requirements of a company....
You have been hired to undertake a review of the corporate governance requirements of a company. The company was started as a private company and has expanded rapidly in the past five years.     The company recently became a publically listed company and the newly created board of directors has concerns that they are unsure of their corporate governance obligations.     The board has given you a very broad brief. Their terms of reference for your reporting requirements encompass describing...
Working with Linked Lists in C++ Tasks As stated in the objectives, you have two methods...
Working with Linked Lists in C++ Tasks As stated in the objectives, you have two methods to implement. These methods (which contain TODO comments) are found in linked_list.cpp. Part 1 Implement the copy constructor; use the LinkedBag as inspiration for your solution as the technique of creating a deep copy is essentially the same. Part 2 Implement the replace method. //linked_list.cpp #include "linked_list.h" // Header file #include <cassert> template<class Object> LinkedList<Object>::LinkedList() : headPtr( nullptr ), itemCount( 0 ) { }...
In this lab you will learn how to use methods from the Math class in order...
In this lab you will learn how to use methods from the Math class in order to calculate the area or the volume of several different shapes. If you are confused about the Methods you can access from the Math class and would like to see some examples click here. Hint: Most of these methods can be done in one line. Step 1 - circleArea In this method you will calculate the area of a circle. Before you can calculate...
sum1Q1: What research methods might you use to update your knowledge of professional and legislative requirements...
sum1Q1: What research methods might you use to update your knowledge of professional and legislative requirements relating to accounting activity statements? (300–400 words)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT