Answered step by step
Verified Expert Solution
Link Copied!
Question
1 Approved Answer

Having issues getting the program to parse through the data file correctly, how can I fix this issue? Here is the suggestion from my professor...

Having issues getting the program to parse through the data file correctly, how can I fix this issue?

Here is the suggestion from my professor...

Looking into your code I have some observations:

  1. the parsing should not be done in the Media class. The superclass should not be aware of its subclasses. Either you do the parsig in each subclass or in the main class.
  2. the lineString[]parts=line.split(";"); means that your input string is split into tokens separated by the semicolon. So your input file should look like
  3. Ebook;123;Forever Young;...

//My code

//Create Media, EBook, MovieDVD, and MusicCD classes

public abstract class Media {

//attributes

private int id;

private String title;

private int year;

private boolean available; // Add an attribute to Media class to store indication when media object is rented versus available

//Add any additional constructors and methods needed to support the below functionality

public Media(int id, String title,int year) {

this.id = id;

this.title = title;

this.year = year;

this.available = true; //boolean check method later on

}

public Media (String line) {

id =(Integer.parseInt(line.substring(line.indexOf("") + 3, line.indexOf(""))));

title = line.substring(line.indexOf("") + 12, line.indexOf("")); //How many numbers long should I make it? 10 too many?

}

//create get and set methods as appropriate

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

//Get Set for title

public String getTitle() {

return title;

}

public void setTitle (String title) {

this.title = title;

}

//Get Set for year

public int getYear() {

return year;

}

public void setYear (int year) {

this.year = year;

}

//Get(is-boolean) Set for available option

public boolean isAvailable() {

return available;

}

public void setAvailable (boolean available) {

this.available = available;

}

//selection to rent a media object based on its id value (user supplies id and should display rental fee value to the user)

public double calculateRentalFee() {

return 2.00; //round easy number

}

public String toString() {

return "Media{id ="+id+", title = "+title+", year = "+year+", availability ="+available+"}";

}

public abstract String serialized();

public static Media parse(String line) {

String[]parts=line.split(";");

Media media;

switch (parts[0]){

case"EBook":

media= new EBook(Integer.parseInt(parts[1]),parts[2],Integer.parseInt(parts[3]), Integer.parseInt(parts[4]));

break;

case"MovieDVD":

media= new MovieDVD(Integer.parseInt(parts[1]),parts[2], Integer.parseInt(parts[3]), Double.parseDouble(parts[4]));

break;

case"MusicCd":

media= new MusicCD(Integer.parseInt(parts[1]),parts[2],Integer.parseInt(parts[3]), Integer.parseInt(parts[4]));

break;

default:

return null;

}

media.setAvailable(Boolean.parseBoolean(parts[5]));

return media;

}

}

import java.util.*;

//Create Media, EBook, MovieDVD, and MusicCD classes

public class EBook extends Media{ //Inherit from parent Media class

//attributes

private int numChapters; //***** Change to pages //******************** Fix this

//Add any additional constructors and methods needed to support the below functionality

public EBook(int id, String title, int year, int chapters) {

super (id, title, year); //parent class

numChapters = chapters; //******************** Fix this

}

//create get and set methods as appropriate

public int getNumChapters() {

return numChapters;

}

public void setNumChapters(int numChapters) {

this.numChapters = numChapters;

}

//selection to rent a media object based on its id value (user supplies id and should display rental fee value to the user)

//Add in some type of poly override

public double calculateRentalFee() { //********************** Fix this

double fee = numChapters * .05;

int currYear= Calendar.getInstance().get(Calendar.YEAR);

if(this.getYear() ==currYear)fee+= 1;//add 1.00 fee

return fee;

}

public String toString() { //******************** Fix this

return"EBook [id= "+ getId() +", title= "+ getTitle()+", year= "+ getYear() +", chapters= "+numChapters+", available = "+ isAvailable() +"]";

}

@Override

public String serialized() { //******************** Fix this Switch from Media needed

return"EBook;"+ getId() +";"+ getTitle() +";"+getYear() +";"+numChapters+";"+ isAvailable();

}

}

//Create Media, EBook, MovieDVD, and MusicCD classes

public class MovieDVD extends Media { //Inherit from parent Media class

//attributes

private double size;// *****************change this to possibly movie length or totalTime

//Add any additional constructors and methods needed to support the below functionality

public MovieDVD (int id, String title, int year, double size) {

super (id, title, year);

this.size = size; //*****************change this to possibly movie length or totalTime

}

public MovieDVD(String line) {

super(line);

setId(Integer.parseInt(line.substring(line.indexOf("") + 4, line.indexOf("")))); //Should these be Set methods???

setTitle(line.substring(line.indexOf("") + 10, line.indexOf("")));

}

//create get and set methods as appropriate

public double getSize() { //*****************change this to possibly movie length or totalTime

return size;

}

public void setSize (double size) { //*****************change this to possibly movie length or totalTime

this.size = size;

}

//selection to rent a media object based on its id value (user supplies id and should display rental fee value to the user)

//Add in some type of poly override

public String toString() {

return"MovieDVD[ id="+ getId() +", title="+ getTitle() +",year="+ getYear() +", size="+size+"MB]"; //*change this to possibly movie length or totalTime

}

public String serialized() { //******************** Fix this Switch from Media needed

return"MovieDVD;"+ getId() +";"+ getTitle() +";"+ getYear()+";"+size+";"+ isAvailable();

}

}

import java.util.*;

//Create Media, EBook, MovieDVD, and MusicCD classes

public class MusicCD extends Media { //Inherit from parent Media class

//attributes

private static int length;

//constructor set up

public MusicCD (int id, String title, int year, int length) {

super (id, title, year);

this.length = length;

}

public MusicCD(String line) {

super(length, line, length);

setId(Integer.parseInt(line.substring(line.indexOf("") + 4, line.indexOf("")))); //Should these be Set methods???

setTitle(line.substring(line.indexOf("") + 10, line.indexOf("")));

}

//Get Set

public int getLength() {

return length;

}

public void setLength(int length) {

this.length = length;

}

// override fee option

@Override

public double calculateRentalFee() {

double fee = length * 0.02;

int currYear = Calendar.getInstance().get(Calendar.YEAR);

if(this.getYear() ==currYear)fee+= 1;

return fee;

}

//override output message

@Override

public String toString() {

return "MusicCd [id="+ getId() +", title="+ getTitle() +",year="+ getYear() +", length="+length+"min]";

}

public String serialized() {

return "MusicCd;"+ getId() +";"+ getTitle() +";"+ getYear() +";"+length+";"+ isAvailable();

}

}

//most of week 8 helpful imports

import java.util.ArrayList;

import java.io.IOException;

import java.util.List;

import java.io.File; //search and load

import java.util.Scanner;

import java.util.stream.Collectors;

public class Manager {

//stores a list of Media objects

private List mediaList;

public Manager() {mediaList = new ArrayList<>();

}

//has functionality to add new Media object to its Media list

public void loadFromFile (String fileName)throws IOException {

try(Scanner scan = new Scanner(new File(fileName))) {

mediaList.clear();

while(scan.hasNextLine()) {

String line = scan.nextLine();

Media media= Media.parse (line);

if(media!= null) {

mediaList.add(media);

}

else {System.err.println (" Can not obtain Media fromline" + line);

}

}

}

}

//has functionality to find all media objects for a specific title and returns that list

public Object findByTitle (String title) {

return mediaList.stream().filter(m-> ((Media)m).getTitle().equals(title)).collect(Collectors.toList());

}

//has functionality to rent Media based on id (updates rental status on media, updates file, returns rental fee)

public Boolean tryRentById(int id) {

Object media = mediaList.stream().filter(m-> ((Media)m).getId() ==id).findAny().orElse(null);if(media==null) {

return null;

}

else {

return false;

}

}

public Media[] findByTitle() {

return null;

}

}

//most of week 8 helpful imports

import java.util.ArrayList;

import java.io.IOException;

import java.util.List;

import java.io.File; //search and load

import java.util.Scanner;

import java.util.stream.Collectors;

import java.util.*; //super helpful, covers everything - saved my life a few times already

public class MediaRentalSystem {

public static void main(String[]args) {

//selection to load Media files from a given directory (user supplies directory)

try( Scanner scan = new Scanner(System.in)) {

boolean isOver = false;

Manager manager = new Manager();

while (!isOver) {

int choice = getMenuOption(scan);

switch (choice) {

case 1:

try {String filename = getStringChoice(scan,"Enter your path (directory) where you would like to load from: ");

manager.loadFromFile(filename);

}

catch (IOException e) {

System.out.println("File can not be opened: System could not load such file ");

}

break;

case 2:

String title = getStringChoice (scan,"Enter Title");List collection= (List)manager.findByTitle(title);

if(collection.isEmpty()) {System.out.println("No media found with this title, try again");

}

else {

for(Media media:manager.findByTitle()) {System.out.println(media);

}

}

break;

case 3:

int id = getIntChoice (scan,"Enter ID",null);

Boolean rent = manager.tryRentById(id);

if (rent==null) {

System.out.println("The media ID-" + id + "not found");

}

else {

if(rent) {System.out.println("Media rental was succesfull, enjoy!");

}

}

break;

case 9:

isOver = true;

break;

default: throw new IllegalStateException();

}

System.out.println(); //spaces after

}

}

System.out.println("Thanks for using BlueBox Media Rental System");

}

private static String title(){

return null;

}

private static int getMenuOption(Scanner scan) {

String builder = "Welcome to the Media Rental system"+System.lineSeparator() +

"1: Load Media"+ System.lineSeparator() +

"2: Find Media"+ System.lineSeparator() +

"3: Rent Media "+ System.lineSeparator() +

"9: Quit Media Rental System"+System.lineSeparator();

System.out.println(builder);

return getIntChoice(scan,"Please enter your selection: ", Arrays.asList (1,2, 3, 9));

}

private static int getIntChoice(Scanner scan, String prompt, Collection options) {

while(true) {

System.out.print(prompt);

try {int choice = Integer.parseInt(scan.nextLine());

if(options==null||options.contains(choice)) {

return choice;

}

else throw new Exception();

}

catch(Exception ignored) {

System.out.println("Invalid input");System.out.println();

}

}

}

private static String getStringChoice(Scanner scan, String prompt) {

while(true) {

System.out.println(prompt);

String choice=scan.nextLine().trim();

if(!choice.isEmpty()) {

return choice;

}

System.out.println ("Invalid input");

System.out.println();

}

}

}

// don't knowif this portion is important or needed

public class Test_Rental{

public static void main(String[]args) {

// create instances of the ebook and display

EBook ebook = new EBook(123,"Forever Young", 2018, 20);

System.out.print(ebook.toString());

System.out.printf(" Rental fee=$%.2f ",ebook.calculateRentalFee());

// create instances of the music cdand display

MusicCD cd = new MusicCD(124,"Beyond Today", 2020, 114);

System.out.print(cd.toString());

System.out.printf(" Rental fee=$%.2f ",cd.calculateRentalFee());

// create instances of the movie dvdand display

MovieDVD dvd = new MovieDVD(125,"After Tomorrow", 2020,120);

System.out.print(dvd.toString());

System.out.printf(" Rental fee=$%.2f ",dvd.calculateRentalFee());

ebook.setNumChapters(25);

System.out.print(" Changing EBook chapters to 25: ");

System.out.println(ebook.toString());

System.out.printf(" New Rental fee=$%.2f ",ebook.calculateRentalFee());

cd.setLength(120);

System.out.print(" Changing MusicCD length to 120: ");

System.out.println(cd.toString());

System.out.printf(" New Rental fee=$%.2f ",cd.calculateRentalFee());

}

//here is my the file sample

EBook;123;"Forever Young";2018;20;true MovieDVD;126;"Forever Young";2020;140.0;false MusicCd;124;Beyond Today;2020;114;2.28

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image
Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Income Tax Fundamentals 2013

Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill

31st Edition

1111972516, 978-1285586618, 1285586611, 978-1285613109, 978-1111972516

More Books

Students explore these related Programming questions