Question

In: Computer Science

IN JAVA USING loops, Arrays, filewriter/reader/exceptions, I dont think we are allowed to use arraylists/algorithm constraints...

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

Solutions

Expert Solution

//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:


Related Solutions

For this question we will be using arrays and classes in Java to compute the min,...
For this question we will be using arrays and classes in Java to compute the min, max, and average value of items for a given array of integers. Complete the following using the base template provided below: -Create methods for min, max, and average and call them from main to print out their values. -Add a method to determine the median (http://www.mathsisfun.com/median.html) and print that value. This method is currently not in the template, so you will need to add...
JAVA I need to write a code that calculates mean and standard deviation using arrays and...
JAVA I need to write a code that calculates mean and standard deviation using arrays and OOP. This is what I have so far. I'm close but my deviation calculator method is throwing errors. Thanks so much :) import java.util.Scanner; import java.util.Arrays; public class STDMeanArray { private double[] tenUserNums = new double[10];//Initialize an array with ten index' private double mean; private double deviation; Scanner input = new Scanner(System.in);//create new scanner object /*//constructor public STDMeanArray(double tenUserNum [], double mean, double deviation){...
We are to make a program about a car dealership using arrays. I got the code...
We are to make a program about a car dealership using arrays. I got the code to display all cars in a list, so I'm good with that. What I'm stuck at is how to make it so when a user inputs x for search, it allows them to search the vehicle. We need two classes, one that shows the car information and another that shows the insert, search, delete, display methods. Here is what I have so far package...
Use JAVA BASICS  classes, aggregation and manipulating arrays of objects. I DO NOT WANT THE SAME SOLUTION...
Use JAVA BASICS  classes, aggregation and manipulating arrays of objects. I DO NOT WANT THE SAME SOLUTION WHICH ALREADY EXISTS ON CHEG. DO NO USE ARRAY LIST Scenario: A dog shelter would like a simple system to keep track of all the dogs that pass through the facility. The system must record for each dog: dogId (int) - must be unique name (string) age (double) - cannot be less than 0 or more than 25 breed (string) sex (char) – m...
Create Kernel of a Strongly Connected Components using Kosaraju's Algorithm in Java. I have to create...
Create Kernel of a Strongly Connected Components using Kosaraju's Algorithm in Java. I have to create a Kernel DAG using the Strongly Connected Components found using Kosaraju's Algorithm. The input to the code is in the format. 5 \n 5 \n 1 0 \n 0 2 \n 2 1 \n 0 3 \n 3 4 The code will find the SCCs and print them to the screen, however, I need to find a way to construct a kernel based on...
For this problem, use the e1-p1.csv dataset. Using the decision tree algorithm that we discussed in...
For this problem, use the e1-p1.csv dataset. Using the decision tree algorithm that we discussed in the class, determine which attribute is the best attribute at the root level. You should not use Weka, JMP Pro, or any other data mining/machine learning software. You must show all intermediate results and calculations. For this problem, use the e1-p1.csv dataset. Using the decision tree algorithm that we discussed in the class, determine which attribute is the best attribute at the root level....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT