In: Computer Science
IN JAVA
USING loops, Arrays, filewriter/reader/exceptions, I dont think we are allowed to use arraylists/algorithm constraints
THE TWO FILES ARE LISTED AFTER THE QUESTION(CDDriver.java and
TextMenu.java)
Lab 14
Array of Objects and File IO
The following exercises are to be completed during lab class. If
you do not have time to finish during lab, they must be completed
before the beginning of the following lab session.
Set-Up
Import the following file (See below)
o CDDriver.java
o TextMenu.java
Import the input file, Collection.txt, into the root of your
project.
Problem
You will be writing a program to manage a list for a CD collection.
Existing CDs are stored in a file. The data in the file (title and
artist) is read into an array. The user will be presented with a
menu with the following choices: add a new CD, display the list, or
quit. You will create one new class and modify an existing
class.
Class diagram and main algorithm
Song
- title:String
- artist:String
+ Song(String title, String artist)
+ toString( ):String
all getters and setters
main algorithm
CREATE array of Song objects
CREATE TextMenu object
READ music collection into array
choice = get menu choice using TextMenu object
2
WHILE (choice != 3)
CASE choice
WHEN 1:
READ data for new song from keyboard
ADD the new song object to the array
INCREMENT count
WRITE the new song data to the file
WHEN 2:
PRINT the array
OTHERWISE:
PRINT "Invalid menu choice. Please try again"
END CASE
PRINT menu
choice = get menu choice using TextMenu object
END WHILE
CLOSE output file
END MAIN
Processing Instructions (write the code in this order) – use the
comments in the program to help with placement.
1. Create the new class called Song.java using the given class
diagram.
There is no default constructor, only the one sending in both
title and artist.
toString - define it so that it prints in the form: title by
artist
2. Write the code for menu choice 2 to print the array to the
screen. Doing this at the beginning allows you to test that the
array has the correct values whenever a change has been made to
it.
You have been given the declarations for:
MAX_ARRAY_SIZE
FILENAME
count (used to keep track of the number of elements currently in
the array)
choice (used to capture the menu choice made by the user)
3. Review the TextMenu class, and write code to create a TextMenu
object with appropriate menu choices. Call the appropriate method
to display the menu and get the user’s choice before the loop and
at the bottom of the loop.
3
Run your program to test getting the menu choice to be sure this
is working correctly.
4. Open the file, read the input data from the file, create a Song
object for each set of data, store the song object in the array.
When done, close the file. Remember to use a try/catch when
attempting to open the file. You will also be keeping track of how
many Song objects are put into the array.
Test this using menu choice 2 to see if everything loaded
correctly.
5. Write the code for the following:
write the output to SongData.txt. Use a try/catch for any
exceptions.
6. Write the code for menu choice 1.
Prompt the user, read the data from the keyboard and create a new
Song object.
Add the song to the array
o Don't forget to add to the count so you know how many items are
in the array
Add the song to the file
7. Close the output file.
8. Run the code. Add a song, then use menu choice 2 to see if it
was added correctly.
FILES NEEDED
/*
* File name: CDDriver.java
*
import java.io.IOException;
public class CDDriver
{ public static void main(String[] args) throws
IOException
{
final int MAX_ARRAY_SIZE =
50;
final String FILENAME =
"Collection.txt";
int count = 0; //
Counter to keep track of number of elements in the array
int choice = 0; // Menu
choice
// Create array to hold song
collection
// Create TextMenu object for menu
(this may involve writing multiple lines of code)
// Read the data from the input file into the array
// Count the elements currently in
the array
// Get the menu choice
while (choice != 3)
{
switch
(choice)
{
case 1:
// Read data for new song to
add to the collection from the keyboard
// Add the song to the
array
// Don't forget to increment
the count
// Add the song to the
file
break;
case 2:
// Print the list
break;
default:
System.out.println("Invalid
menu choice. Please try again.");
}
// Get the menu
choice
}
}
}
****NEXT FILE TextMenu******
package edu.ilstu;
import java.util.*;
/*
* TextMenu.java
*
*/
/**
* TextMenu class
*
*
*/
public class TextMenu
{
private String [] menuItems;
/**
* @param menuItems
* An array of Strings that represent the various menu labels. The
array
* must be the exact size to hold the number of menu items
desired.
*/
public TextMenu(String[] menuItems)
{
this.menuItems = menuItems;
}
/**This method displays the menu and gets a choice from the user.
The choice
* is validated.
*
* @param scan A Scanner object attached to the
keyboard for user input
* @return
* A number between 1 and the number of menu items, representing the
user's choice
*/
public int getChoice(Scanner scan)
{
int choice;
String input;
this.displayMenu();
System.out.print("Please enter your choice(1-" + menuItems.length +
"): ");
input = scan.next();
choice = this.validateChoice(input);
while (choice == -1)
{
System.out.println("That is not a valid choice. Please try
again.");
System.out.print("Enter a number between 1 and " + menuItems.length
+ ": ");
input = scan.next();
choice = this.validateChoice(input);
}
return choice;
}
// displays the menu to the screen
private void displayMenu()
{
System.out.println();
System.out.println();
for (int i = 0; i < menuItems.length; i++)
{
System.out.println(" " + (i+1) + " " + menuItems[i]);
}
System.out.println();
}
// validates the menu choice
private int validateChoice(String input)
{
int choice;
try
{
choice = Integer.parseInt(input);
}
catch (NumberFormatException e)
{
choice = -1;
}
if (choice < 1 || choice > menuItems.length)
{
choice = -1;
}
return choice;
}
***NEXT FILE collection*** really not needed but used for testing I imagine
Ode to Joy
Bach
The Sleeping Beauty
Tchaikovsky
Lullaby
Brahms
Canon
Bach
Symphony No. 5
Beethoven
The Blue Danube Waltz
Strauss
//Song.java
public class Song {
private String title;
private String artist;
public Song(String title, String artist)
{
this.title = title;
this.artist = artist;
}
public void setTitle(String title)
{
this.title =title;
}
public void setArtist(String artist)
{
this.artist = artist;
}
public String getTitle()
{
return title;
}
public String getArtist()
{
return artist;
}
public String toString()
{
return title+" by "+artist;
}
}
//end of Song.java
// TextMenu.java
import java.util.*;
/**
* TextMenu class
*
*
*/
public class TextMenu {
private String [] menuItems;
/**
* @param menuItems
* An array of Strings that represent the various menu
labels. The array
* must be the exact size to hold the number of menu
items desired.
*/
public TextMenu(String[] menuItems)
{
this.menuItems = menuItems;
}
/**This method displays the menu and gets a choice
from the user. The choice
* is validated.
*
* @param scan A Scanner object attached to the
keyboard for user input
* @return
* A number between 1 and the number of menu items,
representing the user's choice
*/
public int getChoice(Scanner scan)
{
int choice;
String input;
this.displayMenu();
System.out.print("Please enter your
choice(1-" + menuItems.length + "): ");
input = scan.next();
choice =
this.validateChoice(input);
while (choice == -1)
{
System.out.println("That is not a valid choice. Please try
again.");
System.out.print("Enter a number between 1 and " + menuItems.length
+ ": ");
input =
scan.next();
choice =
this.validateChoice(input);
}
return choice;
}
// displays the menu to the screen
private void displayMenu()
{
System.out.println();
System.out.println();
for (int i = 0; i <
menuItems.length; i++)
{
System.out.println(" " + (i+1) + " " + menuItems[i]);
}
System.out.println();
}
// validates the menu choice
private int validateChoice(String input)
{
int choice;
try
{
choice =
Integer.parseInt(input);
}
catch (NumberFormatException
e)
{
choice =
-1;
}
if (choice < 1 || choice >
menuItems.length)
{
choice =
-1;
}
return choice;
}
}
//end of TextMenu.java
/*
* File name: CDDriver.java
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class CDDriver {
public static void main(String[] args) throws
IOException {
final int MAX_ARRAY_SIZE =
50;
final String FILENAME =
"Collection.txt";
int count = 0; // Counter to keep
track of number of elements in the array
int choice = 0; // Menu
choice
// Create array to hold song
collection
Song songs[] = new
Song[MAX_ARRAY_SIZE];
// Create TextMenu object for menu
(this may involve writing multiple lines of code)
String menuItems[] = {"Add a new CD", "Display the
list", "Quit"};
TextMenu menu = new TextMenu(menuItems);
String title, artist;
// Read the data from the input file into the
array
// Count the elements currently in the array
try {
Scanner fileScan = new Scanner(new
File(FILENAME));
FileWriter writer = new
FileWriter("SongData.txt");
while(fileScan.hasNextLine())
{
title =
fileScan.nextLine();
artist =
fileScan.nextLine();
songs[count] =
new Song(title,artist);
if(count ==
0)
writer.write(songs[count].toString());
else
writer.write("\n"+songs[count].toString());
count++;
}
fileScan.close();
// Get the menu choice
Scanner scan = new Scanner(System.in);
choice = menu.getChoice(scan);
while (choice != 3)
{
switch (choice)
{
case 1:
// Read data for
new song to add to the collection from the keyboard
if(count <
MAX_ARRAY_SIZE)
{
scan.nextLine();
System.out.print("Title: ");
title = scan.nextLine();
System.out.print("Artist: ");
artist = scan.nextLine();
// Add the song to the array
songs[count] = new Song(title, artist);
// Add the song to the file
writer.write("\n"+songs[count].toString());
// increment the count
count++;
}else
System.out.println("Array is full");
break;
case 2:
// Print the
list
System.out.println("Songs list : ");
for(int
i=0;i<count;i++)
System.out.println(songs[i]);
break;
default:
System.out.println("Invalid menu choice. Please try again.");
}
// Get the menu choice
choice =
menu.getChoice(scan);
}
scan.close();
writer.close();
} catch (FileNotFoundException e) {
System.out.println(FILENAME+" not
found");
}
}
}
//end of CDDriver.java
Output:
Input file:
Console:
Output file: