SlideShare a Scribd company logo
Getting Started
Create a class called Lab8. Use the same setup for setting up your class and main method as you
did for the previous assignments. Be sure to name your file Lab8.java. Additionally, make
another file called Arrays.java. This file will be an object, so simply start it off by declaring an
Arrays class. You can copy the following skeleton and fill in the appropriate code below each of
the comments:
public class Arrays {
/ Instance Variables
// Constructors
// findMin 1
// findMax
// calcSum
// calcAverage
// toString
}
Task Overview
Your task for this lab is to create a class called Arrays with some array processing methods. This
class will maintain an array and the number of elements present in it. Additionally, methods will
be available to display the current min and max elements along with the average of all of them.
Finally, a toString() method will be available to cleanly display all the array elements. Finally,
you will write a simple driver class to test out the above Arrays class.
Part 1: Instance Variables for Arrays
The first thing to do for the Arrays class is to set up its instance variables. Declare the following
(private) instance variables:
• An int array called array ? this will be the array we will be writing methods for.
• An int called count - this represents the number of valid elements in the array.
Part 2:
Constructors for Arrays The Arrays class will have two constructors. The first constructor takes
the maximum size of the array as input as a parameter and initializes the array instance variable
appropriately. It also sets count to size. Finally, it will initialize all of the array elements to some
values between 0 and 10, inclusive. To create this constructor, follow these steps:
• Import java.util.Random to make use of the random number generator.
• Create a constructor with the following header: public Arrays(int size)
• Initialize your array variable and set its size to size (see the chart on page 252 for reference on
initializing arrays). Be very careful that you are setting the value of your array instance variable,
as opposed to creating a new variable called array.
• Set the value of the count variable to size because we will be populating the entire array.
• Copy the following code to the constructor in order to generate random values between 0 and
10, inclusive:
Random rand = new Random();
for (int i = 0; i < count; i++)
{
array[i] = (rand.nextInt(10));
}
Next, create another constructor with the following header: public Arrays(int[] arr). This
constructor will initialize the class by using the passed arr argument in order to fill its instance
variables. The following things need to be done inside of this constructor:
• Set the array variable equal to arr.
• Set the count variable equal to the length of the array.
Part 3: Displaying the Output findMin()
The first method of this class will search the array for the minimum element. Copy the following
code for the findMin method. Note how the count instance variable is used instead of
array.length. This is just in case the entire array is not being used (it will be in our case, though).
public int findMin()
{
int min = array[0]; // Set min to the first element for (int i = 1; i < count; i++)
{
// Reassign min if there is a smaller element
if (array[i] < min)
{ min = array[i];
}
}
return min; // Return the smallest element
}
findMax()
Using the above code as reference, write a method which finds the maximum element within the
array. You can refer to page 259 if you are stuck.
calcSum()
The calcSum() method will be a private method (for clarity, it is the only private method in this
class). It will be used later on within the class as a helper method, but never outside of the class.
This method will return the sum of all of the elements in the array. You can use the following
steps as guidelines for how to complete this method, if you choose:
• Use the following as the header: private int calcSum()
• Declare an int variable for the sum - initialize it to 0
• Write a for loop to iterate through all the elements in the array (remember to use the count
instance variable instead of the length of the array).
• Add the value of each element to the sum.
• Return the sum after the for loop
calcAverage()
This method will return the average of all of the elements in the array. Use the following for the
header of this method: public double calcAverage(). IMPORTANT: Use the calcSum() private
method in your computation of the average for full credit.
Hints:
• You will need to make use of the total elements in the array.
• You will need to cast the result to a double at the appropriate time to achieve an accurate
average
toString()
The toString() method is called whenever an object is passed into a print statement. This
particular toString() method will print the following, assuming the array consists of elements {1,
2, 3, 4}:
[ 1, 2, 3, 4 ]
Copy the following code to use for this method:
public String toString()
{
String output = "[ "; for (int i = 0; i < count; i++)
{
output += array[i];
if (i != count - 1)
{
output += ", ";
}
}
return output + " ]";
}
Part 4:
Test Class for Arrays At this point, the Arrays class is completed. The next step is to create a
driver class to test it. This is the Lab8.java file that you created at the beginning of the lab. Copy
the following code into the main method of the Lab8.java file. This code tests the first
constructor of the Arrays class along with all its methods.
// Create an Arrays object using the first constructor Arrays arr1 = new Arrays(5);
// Print the contents of the array in arr1 System.out.println(arr1);
// Call findMin, findMax, and calcAverage on arr1 and print their values
System.out.println("Min: " + arr1.findMin());
System.out.println("Max: " + arr1.findMax());
System.out.println("Average: " + arr1.calcAverage());
System.out.println();
The next step is to add code which tests the second constructor of the Arrays class. To do this,
complete the following tasks by adding code to the end of the code you just copied into the main
method.
• Create an int array of length 3 - explicitly set its values to any 3 ints by using an array
initialization list. See the chart on the bottom of page 252 for a reference on how to set an array
with initial values.
• Create an Arrays object using the second constructor. Note that this involves passing the array
variable you just created. Call this object arr2.
• Print the arr2 object by passing it into a println statement. • Print the min, max, and average of
the arr2 object, as what was done with the arr1 object.
Sample Output Below is an example of what your output should roughly look like when this lab
is completed. Please note that your values will almost certainly be different, depending both on
the random number generator and the values of the array you created in Lab8.java. The
following run initialized its array in the arr2 object to contain {1, 2, 3}.
Sample Run:
[2, 1, 8, 4, 4]
Min: 1
Max: 8
Average: 3.8
[1, 2, 3]
Min: 1
Max: 3
Average: 2.0
Solution
Arrays.java
import java.util.Random;
public class Arrays {
//Declaring instance variables
private int array[];
private int count;
//Parameterized constructor
public Arrays(int size) {
super();
array = new int[size];
this.count = size;
Random rand = new Random();
for (int i = 0; i < count; i++) {
array[i] = (rand.nextInt(10));
}
}
//Parameterized constructor
public Arrays(int[] arr) {
this.array = arr;
this.count = arr.length;
}
//This method will find the smallest element of an array
public int findMin() {
int min = array[0]; // Set min to the first element
for (int i = 1; i < count; i++) {
// Reassign min if there is a smaller element
if (array[i] < min) {
min = array[i];
}
}
return min; // Return the smallest element
}
//This method will find the maximum element of an array
public int findMax() {
int max = array[0]; // Set max to the first element
for (int i = 1; i < count; i++) {
// Reassign max if there is a smaller element
if (array[i] > max) {
max = array[i];
}
}
return max; // Return the smallest element
}
/* This method will calculate the
* sum of the elements of an array
*/
private int calcSum() {
int sum = 0;
for (int i = 0; i < count; i++) {
sum += array[i];
}
return sum;
}
/* This method will find the average
* of all the elements of an array
*/
public double calcAverage() {
return (double) (calcSum() / count);
}
public String toString() {
String output = "[ ";
for (int i = 0; i < count; i++) {
output += array[i];
if (i != count - 1) {
output += ", ";
}
}
return output + " ]";
}
}
____________________________
Lab8.java
public class Lab8 {
public static void main(String[] args) {
// Create an Arrays object using the first constructor
Arrays arr1 = new Arrays(5);
// Print the contents of the array in arr1
System.out.println(arr1);
// Call findMin, findMax, and calcAverage on arr1 and print their values
System.out.println("Min: " + arr1.findMin());
System.out.println("Max: " + arr1.findMax());
System.out.println("Average: " + arr1.calcAverage());
System.out.println();
int arr[] = { 1, 2, 3 };
Arrays arr2 = new Arrays(arr);
// Print the contents of the array in arr2
System.out.println(arr2);
// Call findMin, findMax, and calcAverage on arr2 and print their values
System.out.println("Min: " + arr2.findMin());
System.out.println("Max: " + arr2.findMax());
System.out.println("Average: " + arr2.calcAverage());
}
}
__________________________
Output:
[ 1, 8, 1, 5, 2 ]
Min: 1
Max: 8
Average: 3.0
[ 1, 2, 3 ]
Min: 1
Max: 3
Average: 2.0
__Thank You

More Related Content

Similar to Getting StartedCreate a class called Lab8. Use the same setup for .pdf

Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
Shahzad
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
JayanthiM19
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
Chap 6 c++Chap 6 c++
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
Everything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdfEverything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdf
firstchoiceajmer
 
ObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docx
vannagoforth
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1sotlsoc
 
Java Sorting CodeImplementing and testing all three sort algorithm.pdf
Java Sorting CodeImplementing and testing all three sort algorithm.pdfJava Sorting CodeImplementing and testing all three sort algorithm.pdf
Java Sorting CodeImplementing and testing all three sort algorithm.pdf
forecastfashions
 
Lecture no 9.ppt operating system semester four
Lecture  no 9.ppt operating system semester fourLecture  no 9.ppt operating system semester four
Lecture no 9.ppt operating system semester four
VaibhavBhagwat18
 
Write a program that will test a name) method no sorting routine from.docx
 Write a program that will test a name) method no sorting routine from.docx Write a program that will test a name) method no sorting routine from.docx
Write a program that will test a name) method no sorting routine from.docx
ajoy21
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01Abdul Samee
 
Array
ArrayArray
Array
PRN USM
 
Net (f#) array
Net (f#)  arrayNet (f#)  array
Net (f#) array
DrRajeshreeKhande
 
Arrays
ArraysArrays
Arrays
ViniVini48
 

Similar to Getting StartedCreate a class called Lab8. Use the same setup for .pdf (20)

Collections
CollectionsCollections
Collections
 
Data Structure In C#
Data Structure In C#Data Structure In C#
Data Structure In C#
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Chap 6 c++
Chap 6 c++Chap 6 c++
Chap 6 c++
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
Everything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdfEverything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdf
 
ObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docxObjectivesMore practice with recursion.Practice writing some tem.docx
ObjectivesMore practice with recursion.Practice writing some tem.docx
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
Java Sorting CodeImplementing and testing all three sort algorithm.pdf
Java Sorting CodeImplementing and testing all three sort algorithm.pdfJava Sorting CodeImplementing and testing all three sort algorithm.pdf
Java Sorting CodeImplementing and testing all three sort algorithm.pdf
 
Lecture no 9.ppt operating system semester four
Lecture  no 9.ppt operating system semester fourLecture  no 9.ppt operating system semester four
Lecture no 9.ppt operating system semester four
 
Write a program that will test a name) method no sorting routine from.docx
 Write a program that will test a name) method no sorting routine from.docx Write a program that will test a name) method no sorting routine from.docx
Write a program that will test a name) method no sorting routine from.docx
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
arrays-120712074248-phpapp01
arrays-120712074248-phpapp01arrays-120712074248-phpapp01
arrays-120712074248-phpapp01
 
Arrays
ArraysArrays
Arrays
 
Array
ArrayArray
Array
 
Net (f#) array
Net (f#)  arrayNet (f#)  array
Net (f#) array
 
LectureNotes-05-DSA
LectureNotes-05-DSALectureNotes-05-DSA
LectureNotes-05-DSA
 
Arrays
ArraysArrays
Arrays
 

More from info309708

Pluto has been hard to measure from Earth because of its atmosphere. .pdf
Pluto has been hard to measure from Earth because of its atmosphere. .pdfPluto has been hard to measure from Earth because of its atmosphere. .pdf
Pluto has been hard to measure from Earth because of its atmosphere. .pdf
info309708
 
Loops and ArraysObjectivesArrays are a series of elements consi.pdf
Loops and ArraysObjectivesArrays are a series of elements consi.pdfLoops and ArraysObjectivesArrays are a series of elements consi.pdf
Loops and ArraysObjectivesArrays are a series of elements consi.pdf
info309708
 
Modern Database Management 11th Edition by Jeffrey A. HofferUse th.pdf
Modern Database Management 11th Edition by Jeffrey A. HofferUse th.pdfModern Database Management 11th Edition by Jeffrey A. HofferUse th.pdf
Modern Database Management 11th Edition by Jeffrey A. HofferUse th.pdf
info309708
 
Let f X Y be a function.True or FalseA sufficient condition for f .pdf
Let f X Y be a function.True or FalseA sufficient condition for f .pdfLet f X Y be a function.True or FalseA sufficient condition for f .pdf
Let f X Y be a function.True or FalseA sufficient condition for f .pdf
info309708
 
Its your third week on the job at Panache Inc. Last week, you made.pdf
Its your third week on the job at Panache Inc. Last week, you made.pdfIts your third week on the job at Panache Inc. Last week, you made.pdf
Its your third week on the job at Panache Inc. Last week, you made.pdf
info309708
 
In JAVA Write a program that uses a two-dimensional array to sto.pdf
In JAVA Write a program that uses a two-dimensional array to sto.pdfIn JAVA Write a program that uses a two-dimensional array to sto.pdf
In JAVA Write a program that uses a two-dimensional array to sto.pdf
info309708
 
How do CCMI model help with the improvements and comparison of the p.pdf
How do CCMI model help with the improvements and comparison of the p.pdfHow do CCMI model help with the improvements and comparison of the p.pdf
How do CCMI model help with the improvements and comparison of the p.pdf
info309708
 
How would you implement a node classs and an edge class to create .pdf
How would you implement a node classs and an edge class to create .pdfHow would you implement a node classs and an edge class to create .pdf
How would you implement a node classs and an edge class to create .pdf
info309708
 
How do you evaluate your own global mind set levelsSolutionAN.pdf
How do you evaluate your own global mind set levelsSolutionAN.pdfHow do you evaluate your own global mind set levelsSolutionAN.pdf
How do you evaluate your own global mind set levelsSolutionAN.pdf
info309708
 
Here are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdf
Here are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdfHere are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdf
Here are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdf
info309708
 
For this homework, you will develop a class called VendingMachine th.pdf
For this homework, you will develop a class called VendingMachine th.pdfFor this homework, you will develop a class called VendingMachine th.pdf
For this homework, you will develop a class called VendingMachine th.pdf
info309708
 
Discuss what is SSH and the advantages and disadvantages of using it.pdf
Discuss what is SSH and the advantages and disadvantages of using it.pdfDiscuss what is SSH and the advantages and disadvantages of using it.pdf
Discuss what is SSH and the advantages and disadvantages of using it.pdf
info309708
 
Describe the differences between the three major physical connection .pdf
Describe the differences between the three major physical connection .pdfDescribe the differences between the three major physical connection .pdf
Describe the differences between the three major physical connection .pdf
info309708
 
Create a student record management system using linked list and queu.pdf
Create a student record management system using linked list and queu.pdfCreate a student record management system using linked list and queu.pdf
Create a student record management system using linked list and queu.pdf
info309708
 
Coca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdf
Coca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdfCoca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdf
Coca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdf
info309708
 
C programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdfC programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdf
info309708
 
Biology LabThe poisonous wastes of diptheria germs are called (A).pdf
Biology LabThe poisonous wastes of diptheria germs are called (A).pdfBiology LabThe poisonous wastes of diptheria germs are called (A).pdf
Biology LabThe poisonous wastes of diptheria germs are called (A).pdf
info309708
 
Aside from the expansion of industrial capitalism, what factors affe.pdf
Aside from the expansion of industrial capitalism, what factors affe.pdfAside from the expansion of industrial capitalism, what factors affe.pdf
Aside from the expansion of industrial capitalism, what factors affe.pdf
info309708
 
Yates (2009) notes that unions have a purpose broader than serving t.pdf
Yates (2009) notes that unions have a purpose broader than serving t.pdfYates (2009) notes that unions have a purpose broader than serving t.pdf
Yates (2009) notes that unions have a purpose broader than serving t.pdf
info309708
 
write a C program for blinking light using function make sure it.pdf
write a C program for blinking light using function make sure it.pdfwrite a C program for blinking light using function make sure it.pdf
write a C program for blinking light using function make sure it.pdf
info309708
 

More from info309708 (20)

Pluto has been hard to measure from Earth because of its atmosphere. .pdf
Pluto has been hard to measure from Earth because of its atmosphere. .pdfPluto has been hard to measure from Earth because of its atmosphere. .pdf
Pluto has been hard to measure from Earth because of its atmosphere. .pdf
 
Loops and ArraysObjectivesArrays are a series of elements consi.pdf
Loops and ArraysObjectivesArrays are a series of elements consi.pdfLoops and ArraysObjectivesArrays are a series of elements consi.pdf
Loops and ArraysObjectivesArrays are a series of elements consi.pdf
 
Modern Database Management 11th Edition by Jeffrey A. HofferUse th.pdf
Modern Database Management 11th Edition by Jeffrey A. HofferUse th.pdfModern Database Management 11th Edition by Jeffrey A. HofferUse th.pdf
Modern Database Management 11th Edition by Jeffrey A. HofferUse th.pdf
 
Let f X Y be a function.True or FalseA sufficient condition for f .pdf
Let f X Y be a function.True or FalseA sufficient condition for f .pdfLet f X Y be a function.True or FalseA sufficient condition for f .pdf
Let f X Y be a function.True or FalseA sufficient condition for f .pdf
 
Its your third week on the job at Panache Inc. Last week, you made.pdf
Its your third week on the job at Panache Inc. Last week, you made.pdfIts your third week on the job at Panache Inc. Last week, you made.pdf
Its your third week on the job at Panache Inc. Last week, you made.pdf
 
In JAVA Write a program that uses a two-dimensional array to sto.pdf
In JAVA Write a program that uses a two-dimensional array to sto.pdfIn JAVA Write a program that uses a two-dimensional array to sto.pdf
In JAVA Write a program that uses a two-dimensional array to sto.pdf
 
How do CCMI model help with the improvements and comparison of the p.pdf
How do CCMI model help with the improvements and comparison of the p.pdfHow do CCMI model help with the improvements and comparison of the p.pdf
How do CCMI model help with the improvements and comparison of the p.pdf
 
How would you implement a node classs and an edge class to create .pdf
How would you implement a node classs and an edge class to create .pdfHow would you implement a node classs and an edge class to create .pdf
How would you implement a node classs and an edge class to create .pdf
 
How do you evaluate your own global mind set levelsSolutionAN.pdf
How do you evaluate your own global mind set levelsSolutionAN.pdfHow do you evaluate your own global mind set levelsSolutionAN.pdf
How do you evaluate your own global mind set levelsSolutionAN.pdf
 
Here are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdf
Here are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdfHere are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdf
Here are two datasetsDataset A 64 65 66 68 70 71 72Dataset B .pdf
 
For this homework, you will develop a class called VendingMachine th.pdf
For this homework, you will develop a class called VendingMachine th.pdfFor this homework, you will develop a class called VendingMachine th.pdf
For this homework, you will develop a class called VendingMachine th.pdf
 
Discuss what is SSH and the advantages and disadvantages of using it.pdf
Discuss what is SSH and the advantages and disadvantages of using it.pdfDiscuss what is SSH and the advantages and disadvantages of using it.pdf
Discuss what is SSH and the advantages and disadvantages of using it.pdf
 
Describe the differences between the three major physical connection .pdf
Describe the differences between the three major physical connection .pdfDescribe the differences between the three major physical connection .pdf
Describe the differences between the three major physical connection .pdf
 
Create a student record management system using linked list and queu.pdf
Create a student record management system using linked list and queu.pdfCreate a student record management system using linked list and queu.pdf
Create a student record management system using linked list and queu.pdf
 
Coca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdf
Coca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdfCoca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdf
Coca-Cola companyStrategic Goals and Objectivesi. Objectives are.pdf
 
C programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdfC programming. Answer question only in C code Ninth Deletion with B.pdf
C programming. Answer question only in C code Ninth Deletion with B.pdf
 
Biology LabThe poisonous wastes of diptheria germs are called (A).pdf
Biology LabThe poisonous wastes of diptheria germs are called (A).pdfBiology LabThe poisonous wastes of diptheria germs are called (A).pdf
Biology LabThe poisonous wastes of diptheria germs are called (A).pdf
 
Aside from the expansion of industrial capitalism, what factors affe.pdf
Aside from the expansion of industrial capitalism, what factors affe.pdfAside from the expansion of industrial capitalism, what factors affe.pdf
Aside from the expansion of industrial capitalism, what factors affe.pdf
 
Yates (2009) notes that unions have a purpose broader than serving t.pdf
Yates (2009) notes that unions have a purpose broader than serving t.pdfYates (2009) notes that unions have a purpose broader than serving t.pdf
Yates (2009) notes that unions have a purpose broader than serving t.pdf
 
write a C program for blinking light using function make sure it.pdf
write a C program for blinking light using function make sure it.pdfwrite a C program for blinking light using function make sure it.pdf
write a C program for blinking light using function make sure it.pdf
 

Recently uploaded

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
rosedainty
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 

Recently uploaded (20)

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)Template Jadual Bertugas Kelas (Boleh Edit)
Template Jadual Bertugas Kelas (Boleh Edit)
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 

Getting StartedCreate a class called Lab8. Use the same setup for .pdf

  • 1. Getting Started Create a class called Lab8. Use the same setup for setting up your class and main method as you did for the previous assignments. Be sure to name your file Lab8.java. Additionally, make another file called Arrays.java. This file will be an object, so simply start it off by declaring an Arrays class. You can copy the following skeleton and fill in the appropriate code below each of the comments: public class Arrays { / Instance Variables // Constructors // findMin 1 // findMax // calcSum // calcAverage // toString } Task Overview Your task for this lab is to create a class called Arrays with some array processing methods. This class will maintain an array and the number of elements present in it. Additionally, methods will be available to display the current min and max elements along with the average of all of them. Finally, a toString() method will be available to cleanly display all the array elements. Finally, you will write a simple driver class to test out the above Arrays class. Part 1: Instance Variables for Arrays The first thing to do for the Arrays class is to set up its instance variables. Declare the following (private) instance variables: • An int array called array ? this will be the array we will be writing methods for. • An int called count - this represents the number of valid elements in the array. Part 2: Constructors for Arrays The Arrays class will have two constructors. The first constructor takes the maximum size of the array as input as a parameter and initializes the array instance variable appropriately. It also sets count to size. Finally, it will initialize all of the array elements to some values between 0 and 10, inclusive. To create this constructor, follow these steps: • Import java.util.Random to make use of the random number generator. • Create a constructor with the following header: public Arrays(int size) • Initialize your array variable and set its size to size (see the chart on page 252 for reference on initializing arrays). Be very careful that you are setting the value of your array instance variable,
  • 2. as opposed to creating a new variable called array. • Set the value of the count variable to size because we will be populating the entire array. • Copy the following code to the constructor in order to generate random values between 0 and 10, inclusive: Random rand = new Random(); for (int i = 0; i < count; i++) { array[i] = (rand.nextInt(10)); } Next, create another constructor with the following header: public Arrays(int[] arr). This constructor will initialize the class by using the passed arr argument in order to fill its instance variables. The following things need to be done inside of this constructor: • Set the array variable equal to arr. • Set the count variable equal to the length of the array. Part 3: Displaying the Output findMin() The first method of this class will search the array for the minimum element. Copy the following code for the findMin method. Note how the count instance variable is used instead of array.length. This is just in case the entire array is not being used (it will be in our case, though). public int findMin() { int min = array[0]; // Set min to the first element for (int i = 1; i < count; i++) { // Reassign min if there is a smaller element if (array[i] < min) { min = array[i]; } } return min; // Return the smallest element } findMax() Using the above code as reference, write a method which finds the maximum element within the array. You can refer to page 259 if you are stuck. calcSum() The calcSum() method will be a private method (for clarity, it is the only private method in this class). It will be used later on within the class as a helper method, but never outside of the class. This method will return the sum of all of the elements in the array. You can use the following
  • 3. steps as guidelines for how to complete this method, if you choose: • Use the following as the header: private int calcSum() • Declare an int variable for the sum - initialize it to 0 • Write a for loop to iterate through all the elements in the array (remember to use the count instance variable instead of the length of the array). • Add the value of each element to the sum. • Return the sum after the for loop calcAverage() This method will return the average of all of the elements in the array. Use the following for the header of this method: public double calcAverage(). IMPORTANT: Use the calcSum() private method in your computation of the average for full credit. Hints: • You will need to make use of the total elements in the array. • You will need to cast the result to a double at the appropriate time to achieve an accurate average toString() The toString() method is called whenever an object is passed into a print statement. This particular toString() method will print the following, assuming the array consists of elements {1, 2, 3, 4}: [ 1, 2, 3, 4 ] Copy the following code to use for this method: public String toString() { String output = "[ "; for (int i = 0; i < count; i++) { output += array[i]; if (i != count - 1) { output += ", "; } } return output + " ]"; } Part 4: Test Class for Arrays At this point, the Arrays class is completed. The next step is to create a driver class to test it. This is the Lab8.java file that you created at the beginning of the lab. Copy
  • 4. the following code into the main method of the Lab8.java file. This code tests the first constructor of the Arrays class along with all its methods. // Create an Arrays object using the first constructor Arrays arr1 = new Arrays(5); // Print the contents of the array in arr1 System.out.println(arr1); // Call findMin, findMax, and calcAverage on arr1 and print their values System.out.println("Min: " + arr1.findMin()); System.out.println("Max: " + arr1.findMax()); System.out.println("Average: " + arr1.calcAverage()); System.out.println(); The next step is to add code which tests the second constructor of the Arrays class. To do this, complete the following tasks by adding code to the end of the code you just copied into the main method. • Create an int array of length 3 - explicitly set its values to any 3 ints by using an array initialization list. See the chart on the bottom of page 252 for a reference on how to set an array with initial values. • Create an Arrays object using the second constructor. Note that this involves passing the array variable you just created. Call this object arr2. • Print the arr2 object by passing it into a println statement. • Print the min, max, and average of the arr2 object, as what was done with the arr1 object. Sample Output Below is an example of what your output should roughly look like when this lab is completed. Please note that your values will almost certainly be different, depending both on the random number generator and the values of the array you created in Lab8.java. The following run initialized its array in the arr2 object to contain {1, 2, 3}. Sample Run: [2, 1, 8, 4, 4] Min: 1 Max: 8 Average: 3.8 [1, 2, 3] Min: 1 Max: 3 Average: 2.0 Solution Arrays.java
  • 5. import java.util.Random; public class Arrays { //Declaring instance variables private int array[]; private int count; //Parameterized constructor public Arrays(int size) { super(); array = new int[size]; this.count = size; Random rand = new Random(); for (int i = 0; i < count; i++) { array[i] = (rand.nextInt(10)); } } //Parameterized constructor public Arrays(int[] arr) { this.array = arr; this.count = arr.length; } //This method will find the smallest element of an array public int findMin() { int min = array[0]; // Set min to the first element for (int i = 1; i < count; i++) { // Reassign min if there is a smaller element if (array[i] < min) { min = array[i]; } } return min; // Return the smallest element } //This method will find the maximum element of an array public int findMax() { int max = array[0]; // Set max to the first element for (int i = 1; i < count; i++) {
  • 6. // Reassign max if there is a smaller element if (array[i] > max) { max = array[i]; } } return max; // Return the smallest element } /* This method will calculate the * sum of the elements of an array */ private int calcSum() { int sum = 0; for (int i = 0; i < count; i++) { sum += array[i]; } return sum; } /* This method will find the average * of all the elements of an array */ public double calcAverage() { return (double) (calcSum() / count); } public String toString() { String output = "[ "; for (int i = 0; i < count; i++) { output += array[i]; if (i != count - 1) { output += ", "; } } return output + " ]"; } } ____________________________
  • 7. Lab8.java public class Lab8 { public static void main(String[] args) { // Create an Arrays object using the first constructor Arrays arr1 = new Arrays(5); // Print the contents of the array in arr1 System.out.println(arr1); // Call findMin, findMax, and calcAverage on arr1 and print their values System.out.println("Min: " + arr1.findMin()); System.out.println("Max: " + arr1.findMax()); System.out.println("Average: " + arr1.calcAverage()); System.out.println(); int arr[] = { 1, 2, 3 }; Arrays arr2 = new Arrays(arr); // Print the contents of the array in arr2 System.out.println(arr2); // Call findMin, findMax, and calcAverage on arr2 and print their values System.out.println("Min: " + arr2.findMin()); System.out.println("Max: " + arr2.findMax()); System.out.println("Average: " + arr2.calcAverage()); } } __________________________ Output: [ 1, 8, 1, 5, 2 ] Min: 1 Max: 8 Average: 3.0 [ 1, 2, 3 ] Min: 1 Max: 3 Average: 2.0 __Thank You