SlideShare a Scribd company logo
1 of 10
Download to read offline
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.
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(" Enter 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(" Enter 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(" 1) 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(" 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  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  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

More Related Content

Similar to Objectives In this lab you will review passing arrays to methods and.pdf

Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
iammukesh1075
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
tameemyousaf
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
Rahul04August
 
Please the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdfPlease the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdf
admin463580
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
BackPack3
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
BackPack3
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
BackPack3
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
BackPack3
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
ssuseraef9da
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
BackPack3
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
ssuseraef9da
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
arwholesalelors
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
BackPack3
 

Similar to Objectives In this lab you will review passing arrays to methods and.pdf (20)

Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.Operator overloading in c++ is the most required.
Operator overloading in c++ is the most required.
 
lecture12.ppt
lecture12.pptlecture12.ppt
lecture12.ppt
 
Arrays Fundamentals Unit II
Arrays  Fundamentals Unit IIArrays  Fundamentals Unit II
Arrays Fundamentals Unit II
 
03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays03 stacks and_queues_using_arrays
03 stacks and_queues_using_arrays
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
 
Lecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structureLecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structure
 
CHAPTER 5
CHAPTER 5CHAPTER 5
CHAPTER 5
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
 
Please the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdfPlease the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdf
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
 
#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf#include algorithm #include vector #include iostream usi.pdf
#include algorithm #include vector #include iostream usi.pdf
 

More from f3apparelsonline

Client Business Risk The risk that the client will fail to achieve it.pdf
Client Business Risk The risk that the client will fail to achieve it.pdfClient Business Risk The risk that the client will fail to achieve it.pdf
Client Business Risk The risk that the client will fail to achieve it.pdf
f3apparelsonline
 
create a new interface called DropoutStackADT for representing a dro.pdf
create a new interface called DropoutStackADT for representing a dro.pdfcreate a new interface called DropoutStackADT for representing a dro.pdf
create a new interface called DropoutStackADT for representing a dro.pdf
f3apparelsonline
 
Base your answer to questio n 25 on the map below and on your knowled.pdf
Base your answer to questio n 25 on the map below and on your knowled.pdfBase your answer to questio n 25 on the map below and on your knowled.pdf
Base your answer to questio n 25 on the map below and on your knowled.pdf
f3apparelsonline
 
As presented, the tree summation algorithm was always illustrated wi.pdf
As presented, the tree summation algorithm was always illustrated wi.pdfAs presented, the tree summation algorithm was always illustrated wi.pdf
As presented, the tree summation algorithm was always illustrated wi.pdf
f3apparelsonline
 
4. Which one of the following is a key disadvantage of a a. As a gene.pdf
4. Which one of the following is a key disadvantage of a a. As a gene.pdf4. Which one of the following is a key disadvantage of a a. As a gene.pdf
4. Which one of the following is a key disadvantage of a a. As a gene.pdf
f3apparelsonline
 
Use Java to program the following.1. Create public java class name.pdf
Use Java to program the following.1. Create public java class name.pdfUse Java to program the following.1. Create public java class name.pdf
Use Java to program the following.1. Create public java class name.pdf
f3apparelsonline
 
To design an expert system, we must first identify a problem to be s.pdf
To design an expert system, we must first identify a problem to be s.pdfTo design an expert system, we must first identify a problem to be s.pdf
To design an expert system, we must first identify a problem to be s.pdf
f3apparelsonline
 

More from f3apparelsonline (20)

How do the microsporangium and microspore in seed plants differ from.pdf
How do the microsporangium and microspore in seed plants differ from.pdfHow do the microsporangium and microspore in seed plants differ from.pdf
How do the microsporangium and microspore in seed plants differ from.pdf
 
Homework question with 2 partsA. Compare and contrast the geologic.pdf
Homework question with 2 partsA. Compare and contrast the geologic.pdfHomework question with 2 partsA. Compare and contrast the geologic.pdf
Homework question with 2 partsA. Compare and contrast the geologic.pdf
 
Client Business Risk The risk that the client will fail to achieve it.pdf
Client Business Risk The risk that the client will fail to achieve it.pdfClient Business Risk The risk that the client will fail to achieve it.pdf
Client Business Risk The risk that the client will fail to achieve it.pdf
 
Describe how removing water from a hydrophobic binding site or ligan.pdf
Describe how removing water from a hydrophobic binding site or ligan.pdfDescribe how removing water from a hydrophobic binding site or ligan.pdf
Describe how removing water from a hydrophobic binding site or ligan.pdf
 
create a new interface called DropoutStackADT for representing a dro.pdf
create a new interface called DropoutStackADT for representing a dro.pdfcreate a new interface called DropoutStackADT for representing a dro.pdf
create a new interface called DropoutStackADT for representing a dro.pdf
 
Case Project 7-1 commen, diicrerne functions, arii price. wri.pdf
Case Project 7-1 commen, diicrerne functions, arii price. wri.pdfCase Project 7-1 commen, diicrerne functions, arii price. wri.pdf
Case Project 7-1 commen, diicrerne functions, arii price. wri.pdf
 
Base your answer to questio n 25 on the map below and on your knowled.pdf
Base your answer to questio n 25 on the map below and on your knowled.pdfBase your answer to questio n 25 on the map below and on your knowled.pdf
Base your answer to questio n 25 on the map below and on your knowled.pdf
 
As presented, the tree summation algorithm was always illustrated wi.pdf
As presented, the tree summation algorithm was always illustrated wi.pdfAs presented, the tree summation algorithm was always illustrated wi.pdf
As presented, the tree summation algorithm was always illustrated wi.pdf
 
A person who quits a job in Los Angeles to look for work in Chicago i.pdf
A person who quits a job in Los Angeles to look for work in Chicago i.pdfA person who quits a job in Los Angeles to look for work in Chicago i.pdf
A person who quits a job in Los Angeles to look for work in Chicago i.pdf
 
4. Which one of the following is a key disadvantage of a a. As a gene.pdf
4. Which one of the following is a key disadvantage of a a. As a gene.pdf4. Which one of the following is a key disadvantage of a a. As a gene.pdf
4. Which one of the following is a key disadvantage of a a. As a gene.pdf
 
Who are the three agencies today that rate bondsHow do the three .pdf
Who are the three agencies today that rate bondsHow do the three .pdfWho are the three agencies today that rate bondsHow do the three .pdf
Who are the three agencies today that rate bondsHow do the three .pdf
 
Which of the following is trueChimpanzees and hominids share a comm.pdf
Which of the following is trueChimpanzees and hominids share a comm.pdfWhich of the following is trueChimpanzees and hominids share a comm.pdf
Which of the following is trueChimpanzees and hominids share a comm.pdf
 
What does the multicellular Volvox and unicellular Chlamydomonas sug.pdf
What does the multicellular Volvox and unicellular Chlamydomonas sug.pdfWhat does the multicellular Volvox and unicellular Chlamydomonas sug.pdf
What does the multicellular Volvox and unicellular Chlamydomonas sug.pdf
 
What is the firm’s cost of preferred stock Please show work in Exce.pdf
What is the firm’s cost of preferred stock Please show work in Exce.pdfWhat is the firm’s cost of preferred stock Please show work in Exce.pdf
What is the firm’s cost of preferred stock Please show work in Exce.pdf
 
What are the 2 major cytoskeletal classes that participate in cell d.pdf
What are the 2 major cytoskeletal classes that participate in cell d.pdfWhat are the 2 major cytoskeletal classes that participate in cell d.pdf
What are the 2 major cytoskeletal classes that participate in cell d.pdf
 
Wanda is a 20 percent owner of Video Associates, which is treated as.pdf
Wanda is a 20 percent owner of Video Associates, which is treated as.pdfWanda is a 20 percent owner of Video Associates, which is treated as.pdf
Wanda is a 20 percent owner of Video Associates, which is treated as.pdf
 
Use Java to program the following.1. Create public java class name.pdf
Use Java to program the following.1. Create public java class name.pdfUse Java to program the following.1. Create public java class name.pdf
Use Java to program the following.1. Create public java class name.pdf
 
To design an expert system, we must first identify a problem to be s.pdf
To design an expert system, we must first identify a problem to be s.pdfTo design an expert system, we must first identify a problem to be s.pdf
To design an expert system, we must first identify a problem to be s.pdf
 
Translate the following into English. Let C denote an arbitrary coll.pdf
Translate the following into English. Let C denote an arbitrary coll.pdfTranslate the following into English. Let C denote an arbitrary coll.pdf
Translate the following into English. Let C denote an arbitrary coll.pdf
 
The force on an object is F = - 21j. For the vector v = 2 i - 2j, fin.pdf
The force on an object is F = - 21j. For the vector v = 2 i - 2j, fin.pdfThe force on an object is F = - 21j. For the vector v = 2 i - 2j, fin.pdf
The force on an object is F = - 21j. For the vector v = 2 i - 2j, fin.pdf
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
ssuserdda66b
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Recently uploaded (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 

Objectives In this lab you will review passing arrays to methods and.pdf

  • 1. 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. 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");
  • 2. //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
  • 3. 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(" Enter 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
  • 4. 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(" Enter the poistion to remove a number: "); int position = scanner.nextInt();
  • 5. //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(" 1) Display Reverse order");
  • 6. 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(" Enter your choice: "); ch = scanner.nextInt(); switch(ch)
  • 7. { //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 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 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
  • 8. 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
  • 9. 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: