Objectives • Be able to declare and instantiate arrays • Be able to fill an arra
ID: 3817399 • Letter: O
Question
Objectives
• Be able to declare and instantiate arrays
• Be able to fill an array using a for loop
• Be able to access and process data in an array
• Be able to write a sorting method
• Be able to use an array of objects
Introduction
Everyone is familiar with a list. We make shopping lists, to-do lists, assignment lists, birthday lists, etc. Notice that though there may be many items on the list, we call the list by one name. That is the idea of the array, one name for a list of related items. In this lab, we will work with lists in the form of an array.
It will start out simple with a list of numbers. We will learn how to process the contents of an array. We will also explore sorting algorithms, using the selection sort.
We will then move onto more complicated arrays, arrays that contain objects.
Task #1 Average Class
Create a class called Average according to the UML diagram.
Average
- data [ ]: int
- mean: double
+ Average( )
+ calculateMean(): void
+ toString(): String
+ selectionSort() : void
This class will allow a user to enter 5 scores into an array. It will then rearrange the
data in descending order and calculate the mean for the data set.
Attributes:
• data[]—the array which will contain the scores
• mean—the arithmetic average of the scores
Methods:
• Average—the constructor. It will allocate memory for the array. Use a for loop to repeatedly display a prompt for the user which should indicate that user should enter score number 1, score number 2, etc. Note: The computer starts counting with 0, but people start counting with 1, and your prompt should
account for this. For example, when the user enters score number 1, it will be stored in indexed variable 0. The constructor will then call the selectionSort and the calculateMean methods.
• calculateMean—this is a method that uses a for loop to access each score in the array and add it to a running total. The total divided by the number of scores (use the length of the array), and the result is stored into mean.
• toString—returns a String containing data in descending order and the
mean.
• selectionSort—his method uses the selection sort algorithm to rearrange
the data set from highest to lowest.
Task #2 Average Driver
1. Create an AverageDriver class. This class only contains the main method. The main method should declare and instantiate an Average object. The Average object information should then be printed to the console.
2. Compile, debug, and run the program. It should output the data set from highest
to lowest and the mean. Compare the computer’s output to your hand calculation
using a calculator. If they are not the same, do not continue until you correct
your code.
Task #3 Arrays of Objects
1. I will provide the following code files for you to complete Song.java (code listing 7.1), CompactDisc.java (code listing 7.2), and Classics.txt (code listing 7.3).
Song.java is complete and will not be edited. Classics.txt is the data file that will be used by CompactDisc.java, the file you will be editing.
2. In CompactDisc.java, there are comments indicating where the missing code is
to be placed. Declare an array of Songs, called cd, to be of size 6.
3. Fill the array by creating a new song with the title and artist and storing it in
the appropriate position in the array.
4. Print the contents of the array to the console.
5. Compile, debug, and run. Your output should be as follows:
Contents of Classics
Ode to Joy by Bach
The Sleeping Beauty by Tchaikovsky
Lullaby by Brahms
Canon by Bach
Symphony No. 5 by Beethoven
The Blue Danube Waltz by Strauss
Task #4:
Please include the following files in a compress folder name Lab7_ABcd.zip, A = upper case first name initial, Bcd = full last name with uppercase letter, no space in file name.
Average.java, AverageDriver.java, Classics.txt, CompactDisc.java, Song.java, and all the .class files. Total of 9 files plus a screen output file paste below total of 10 files (including this document).
Codes provided for task #3 and 4:
Song.java:
public class Song
{
private String title;
private String artist;
public Song(String title, String artist)
{
this.title = title;
this.artist = artist;
}
public String toString()
{
return title + " by " + artist + " ";
}
}
CompactDisc:
//This program creates a list of songs for a CD by reading from a file
import java.io.*;
import java.util.Scanner;
public class CompactDisc
{
public static void main(String [] args) throws IOException
{
File file = new File("Classics.txt");
Scanner input = new Scanner(file);
String title;
String artist;
//Declare an array of songs, called cd, of size 6
for (int i = 0; i < cd.length; i++)
{
title = input.nextLine();
artist = input.nextLine();
// fill the array by creating a new song with
// the title and artist and storing it in the
// appropriate position in the array
}
System.out.println("Contents of Classics:");
for (int i = 0; i < cd.length; i++)
{
//print the contents of the array to the console
}
}
}
Classics.txt:
Ode to Joy
Bach
The Sleeping Beauty
Tchaikovsky
Lullaby
Brahms
Canon
Bach
Symphony No. 5
Beethoven
The Blue Danube Waltz
Strauss
Thank You!!!!!
Average
- data [ ]: int
- mean: double
+ Average( )
+ calculateMean(): void
+ toString(): String
+ selectionSort() : void
Explanation / Answer
Task #1 Average Class
import java.util.Scanner;
public class Average {
int[] data;
double mean;
public Average(){
data = new int[5];
Scanner s = new Scanner(System.in);
for(int i=0;i<5;i++)
{
System.out.print("Enter score number "+(i+1)+": ");
data[i] = s.nextInt(); //Taking input and storing in array
}
selectionSort(); //Sort data in descending order
calculateMean(); //Calculate mean of data
s.close();
}
public void calculateMean(){
double sum=0;
for(int i=0;i<5;i++)
{
sum += data[i]; //Sum of data
}
mean = sum/data.length; //Calculate mean
}
public String toString()
{
//Return the string containing data in descending order and their averge
String str="Scores in descending order: ";
for(int i=0;i<data.length;i++)
str += data[i]+" ";
str += " Mean of scores: "+ mean;
return str;
}
public void selectionSort()
{
int small,i,j,pos;
for(i=0;i<data.length-1;i++)
{
//Initialize small and pos with value and index of current element respectively
small=data[i];
pos=i;
for(j=i+1;j<data.length;j++)
{
if(data[j]>small) //a number found which is smaller than current element
{
small=data[j];
pos=j;
}
}
//Swap the smaller element with current element
int temp = data[pos];
data[pos] = data[i];
data[i] = temp;
}
}
}
Task #2 Average Driver
package com.code.programs.chegg;
public class AverageDriver {
public static void main(String[] args)
{
//Create object of Average class
Average average = new Average();
System.out.println(average); //Show object information
}
}
Output
Enter score number 1: 1
Enter score number 2: 2
Enter score number 3: 3
Enter score number 4: 4
Enter score number 5: 5
Scores in descending order: 5 4 3 2 1
Mean of scores: 3.0
Updated code for CompactDisc.java
import java.io.*;
import java.util.Scanner;
public class CompactDisc
{
public static void main(String [] args) throws IOException
{
File file = new File("Classics.txt");
Scanner input = new Scanner(file);
String title;
String artist;
//Declare an array of songs, called cd, of size 6
Song[] cd = new Song[6];
for (int i = 0; i < cd.length; i++)
{
title = input.nextLine();
artist = input.nextLine();
// fill the array by creating a new song with
// the title and artist and storing it in the
// appropriate position in the array
Song song = new Song(title,artist);
cd[i] = song;
}
System.out.println("Contents of Classics:");
for (int i = 0; i < cd.length; i++)
{
//print the contents of the array to the console
System.out.print(cd[i]);
}
}
}
Output
Contents of Classics:
Ode to Joy by Bach
The Sleeping Beauty by Tchaikovsky
Lullaby by Brahms
Canon by Bach
Symphony No. 5 by Beethoven
The Blue Danube Waltz by Strauss
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.