I'm creating an interface that manage the booking of Cinema tickets in different weeks/theatres.
I have a Film Class:
public class Film {
private String title;
private Double price;
private String ageRestriction;
private double rating;
private String genre;
private String location;
private String screenDay;
}
A FilmList class that create and store all the Films in an ArrayList:
public class FilmList {
private ArrayList <Film> filmArrayList;
public FilmList (){
this.filmArrayList = new ArrayList<>();
}
public void addFilm(Film films){
this.filmArrayList.add(films);
}
And this is the graphic unit interface. What I'm trying to do is to catch in the ArrayList just one element based on two condition:
The Week and the Theatre selected from the user and also add a way for check that there's just one element on the list from the chosen parameters. This is important because each film instance will be called and "setted" on the Label of the FXML file (and because I'm thinking to implement an interface for add films in the ArrayList).
Thank's everyone.
OK, so in your example it would be something like following:
//try to find any movie that suits two predicates, 1st - that it's price is greater than 30( this is random number, you can put a value from your textfield here ) and 2nd - that it's title contains Spiderman ( again, put a value from your textfield title search here for your need )
Optional<Film> movie = listOfMovies.stream().filter(i -> i.getPrice() > 30 && i.getTitle.contains("Spiderman")).findAny();
// if any movie has been found to suits provided criterias
if(movie.isPresent())
{
//print it on screen, note method get()
//again this is just for example here, in your code,
// you can do with this result whatever you like
// for example show all data about that movie on screen
System.out.println("---->" +movie.get());
}
else
{
// if not found do nothing
System.out.println("Nothing found...");
}
More about Optional can be found here.
Related
I have to do a project for my beginners Java class that has to do with inheritance.
The MediaItem class encapsulates the data required to represent a MediaItem. Here is the code that was already given:
public class MediaItem {
protected String title;
protected String author;
protected String genre;
/* Subclasses may add specific parameters to their constructor's
* parameter lists.
*/
public MediaItem(String title, String author, String genre){
this.title = title;
this.author = author;
this.genre = genre;
}
// get method for the title
public String getTitle(){
return title;
}
// get method for the author
public String getAuthor(){
return author;
}
// get method for the genre
public String getGenre(){
return genre;
}
// Subclasses should override.
public String toString(){
return title+", "+author+", "+genre;
}
}
The MediaList class encapsulates a list of media items in a user's collection. The list is implemented as an ArrayList of type MediaList. Each type of media item is represented by an instance of the Book, Movie, Podcast, or Song class. These classes are subclasses of MediaItem. The list stores media items as references of type MediaItem.
Here is the code for adding and removing an item in MediaList:
public void addItem(MediaItem newItem){
itemList.add(newItem);
}
public boolean removeItem(String targetTitle, String targetAuthor){
boolean result = false;
for (MediaItem media : itemList) {
if(itemList.contains(targetTitle) && itemList.contains(targetAuthor)){
itemList.remove(media);
result = true;
} else {
result = false;
}
}
return result;
}
When this test runs with Junit, an error is thrown saying there expected size was <1> but it should be <0>
When I run it and answer the prompts, it says the media item is added but when I try to remove the media item it says "Could not find Black Panther in the library, nothing removed."
#Test
public void addOneRemoveOneItemUpdateSizeTest() {
MediaItem item = new Movie("Black Panther", "Coogler", "fantasy", 134, "Chadwick Boseman", "2018");
mediaList.addItem(item);
mediaList.removeItem("Black Panther", "Coogler");
int studentSize = mediaList.getNumItems();
assertEquals("Test 30: Add item, remove item size is 0.", 0, studentSize);
Movie class
public class Movie extends MediaItem {
public Movie(String title, String author, String genre,
int playTime, String leadActor, String releaseYear){
super(title, author, genre);
playTime = 0;
leadActor = "noLead";
releaseYear = "noRelease";
}
public int getPlayTime(){
return playTime;
}
public String getLeadActor(){
return leadActor;
}
public String getReleaseYear(){
return releaseYear;
}
#Override
public String toString(){
super.toString();
return "Movie: " + title + ", " + author + ", " + genre + ", " + playTime + ", " + leadActor + ", " + releaseYear;
}
}
Is my removeItem method wrong? I don't understand why the title can't be found. Can someone point me in the right direction?
I think the problem is this if statement:
if(itemList.contains(targetTitle) && itemList.contains(targetAuthor)){
It should be
if (media.getTitle().equals(targetTitle) && media.getAuthor().equals(targetAuthor))
In other words, you need to check whether each media item, rather than the list, has the right title and author.
There are two correction points for this code:-
The conditional statement is not correct
Deletion is being done incorrectly & it will lead to ConcurrentModification Exception
1. Conditional Statement Bug Explanation
The contains() method checks for the existence of passed object in the list. It is handy while dealing with wrapper classes or String class but whenever we have our custom data types such as classes and use case demands to remove the object on the basis of certain properties then this method may not be helpful.
Right now your code is checking for the String objects in your arguments 'targetTitle' and 'targetAuthor' and thus fail to remove the desired object from your list.
Your use case demands the removal of object from list on the basis of 'title' and 'author' which are the properties(instance variables) of MediaItem class and hence when you are traversing through all the objects in the list you should check the respective instance variables of the objects that you are traversing in the List.
Kindly use '==' instead of equals() method as you will have to do explicit null checks otherwise you can end up having NullPointer exception.
2. Incorrect Deletion from List
You are making the modification on the same object which you are traversing via for-each(Enhanced for) loop. You should make use of iterator object for this purpose. Please go through this link for further information.Using iterator for deleting elements in collection
I think you are removing item in the wrong way. You should remove item from list by using iterator or loop from the end of list.
Futhermore, the conditional statements is wrong too, you should use String.equals to check item's attributes that match inputs. In addition, you ought to validate input to prevent Null Pointer Exception.
I am creating a commercial software and got stuck in place, where I need to fill an Array with information from multiple JTextBox fields.
I created an Array -
public String[][] BookAttributes = new String[BookRows][BookLines];
I want to save information added by User from following JTextFields in [BookLines] column for each book, which should auto-increment every time when new book is added to stock.
private JTextField tfBookName;
private JTextField tfBookCost;
private JTextField tfBookYearOfPublication;
private JTextField tfBookPublishingHouse;
private JTextField tfBookISBN;
private JTextField tfBookAuthor;
private JTextField tfBookNrOfPages;
Unfortunately, I cannot find a solution how to put this all together.
Any Help appreciated.
Thank you!
If I understood you correctly then you are looking to save the Book information like Name, Cost etc. to an array.
But, in the above case you are creating a 2-D String Array which looks something like this:
Location (0,0) of array -> "foo"
Location (0,1) of array -> "bar"
...
...
What you actually need is a class say, Book which can hold the information regarding the different attributes. Something like as follows:
public class Book {
private String bookName;
private String bookCost;
private String bookYearOfPublication;
private String bookPublishingHouse;
private String bookISBN;
private String bookAuthor;
private String bookNrOfPages;
/* Constructor, Getter, Setters */
...
}
Next you can create an array of this class like this:
int bookRows = 100;
Book[] booksInfo = new Book[bookRows];
And simply code a for loop for stroing the different book details as follows:
for(int i = 0; i < bookRows; i++) {
Book book = new Book();
book.setBookName(tfBookName);
...
...
booksInfo[i] = book;
}
You can further override the toString() method of the Book class if you want to print the different attributes of any book by simply using System.out.println(...).
Here is the code snippet:
#Override
public String toString() {
return new StringBuilder().append("BookName: ").append(bookName)
.append(" | Book Cost: ").append(bookCost).toString();
}
I've hit a roadblock with this program.
I have a program that involves creating a program that involves the "inventory" of Cadillac, and among all else, I cannot find answers to my questions.
I just do not know what to do. I'll provide the directions and then post the syntax I have so far.
Here is what I have to do:
inventory for a fictional Cadillac Dealership and allows the inventory to be searched to display a list of cars that meet specific criteria.
create an ADT class called Cadillac which contains four fields of instance data: Strings for model name, stock number and color, and an integer for price. The class contains one Constructor, which receives values for all four instance fields, and assigns the parameter values to the instance variables. The class also contains a simple accessor method and mutator method for each field of instance data.
When the program is ran, it loads the inventory from a file, "inventory.dat".
Here is a sample of the contents of the file:
DTS 11210 Glacier White 42706
Escalade 66502 Crimson Pearl 65547
XLR 58362 Radiant Bronze 78840
SRX 16218 Radiant Bronze 44522
Each line (each record) contains 4 fields of data: strings for model name, a 5–digit stock number, and color, and an integer for price. The delimiter between the fields is a tab character (“\t”).
In main(), create an array of Cadillac objects, read in a record from the file, split it into its 4 fields, create a Cadillac object and add it to the array.
the inventory file changes and your program needs to work no matter how many records are in the file. You are guaranteed there will never be more than 100 records in the file (they only have room for 100 cars on the lot), and that each record will contain exactly 4 fields of valid data.
The user can search the inventory two ways: by model name and by price. After you load the inventory, ask the user which search they want to do. If they indicate “by model name”, have them enter the name to search for. The valid model names are: DTS, Escalade, ESV, EXT, SRX, STS, and XLR. Search the inventory for all cars with that name and display a table of results on the console screen.
-When the user indicates he/she wants to search by price, have them enter the price to search
for, then perform the search, displaying all cars that have a price within $3,000 of the search
price.
- The program should loop to do as many searches as the user wants. Let the user end the
program by clicking a “Cancel” button when asked for the type of search they want to perform.
A “Cancel” button on the second question (the model or price to search for) should not end the
program, but your code should recognize it as an invalid entry, and not throw an exception.
Besides the list output, all input and output in the program should be with JOptionPane dialogs.
Here is what I have so far:
import java.util.Scanner;
import java.io.*;
public class Inventory {
public static void main ( String[] args )
{
String line;
String[] fields;
String[] items;
int count = 0;
int recCount;
Cadillac[] list = new Cadillac[100];
try
{
BufferedReader br = new BufferedReader( new FileReader( "inventory.dat" ) );
line = br.readLine();
while( line != null )
{
fields = line.split( "\t" );
items[count++] = new Cadillac( fields[0], fields[1], fields[2],
fields[3] );
line = br.readLine();
}
br.close();
}
catch( IOException e )
{
System.out.println( "Can't open input file. Program terminating." );
System.exit( 1 );
}
}
public static int loadArray(Cadillac[] items)
{
}
}
class Cadillac {
//Instance data
private String model;
private String stockNum;
private String color;
private int price;
//Constructor
public Cadillac(String mdl, String stckNum, String clr, int prc)
{
model = mdl;
stockNum = stckNum;
color = clr;
price = prc;
}
//Set of Accessor and Mutator Methods
public String getModel(){
return model;
}
public void setModel(String newModel){
model = newModel;
}
public String getStockNum(){
return stockNum;
}
public void setStockNum(String newStockNum){
stockNum = newStockNum;
}
public String getColor(){
return color;
}
public void setColor(String newColor){
color = newColor;
}
public int getPrice(){
return price;
}
public void setPrice(int newPrice){
price = newPrice;
}
}
PLEASE HELP! I do not have any other idea of what to do.
In regards to your comment:
It is saying that it cannot find the symbol constructor Cadillac
Your only constructor defined for Cadillac has parameters (String, String, String, int) but when you try to instantiate the object in main, you pass it four Strings. Java is throwing an error because it can't find the correct constructor.
Either pass the last parameter as an int or create a new constructor for your arguments.
Your most immediate problem is that the signature of your data objects constructor is incompatible with the way you are calling it. You have declared your constructor as so:
public Cadillac(String mdl, String stckNum, String clr, int prc)
It takes three string arguments and an int, but you are calling it with four strings:
new Cadillac( fields[0], fields[1], fields[2], fields[3] );
Thats the source of the compile error you reported seeing. You should convert your last String to an int.
new Cadillac( fields[0], fields[1], fields[2], Integer.parseInt(fields[3]).intValue() );
Apart from that there is another glaring error in your code. You declare an array of strings, but are attempting to store instances of 'Cadillac' into it:
String[] items;
// ...
items[count++] = new Cadillac( ... );
I won't code your entire homework for you, but my advise would be to first right down in plain English sentences, each task that needs to be accomplished in order to complete the overall program. Then start translating each individual sentence into code, ideally in the form of methods on your classes that can be called. As you run into issues, come back and ask specific questions and I'm sure there will be someone here willing to help you more.
Good luck.
I'm writing a program in which it will asks the user to enter some entries like Name, Surname etc and then store all those entries in one location of an arraylist. In other words variables ( name, surname, telephone ) will be added to location 0 of arraylist.
The difficulty I'm finding is when it comes to get all those variables and store them into the location of the array list. Can someone help me ? Thanks.
public class Loans
{
ArrayList lns = new ArrayList();
void LoansInput ()
{
// Add New Loan Button
// Requesting DVD ID
String dvdid;
dvdid =JOptionPane.showInputDialog("Enter DVD ID Number");
// Requesting Member Name & Surname
String namesurname;
namesurname = JOptionPane.showInputDialog("Client Name & Surname");
// Requesting Member ID Number
String mid;
mid =JOptionPane.showInputDialog("Client ID Number");
// Requesting Member ID Number
String telephone;
telephone =JOptionPane.showInputDialog("Client Telephone Number");
// Requesting Rental Date
String rentaldate;
rentaldate =JOptionPane.showInputDialog("Rental Date (DD-MM-YY)");
// Requesting Return Date
String returndate;
returndate =JOptionPane.showInputDialog("Return Date (DD-MM-YY)");
What should I add here in order to get all this variables and put them in the Arraylist lns in one location? (Not every entry in different locations)
A good approach would be to create a User object, e.g., (getters and setters left out)
public class User {
private Stringg surname;
private String memberId;
private String telephone;
// etc.
}
Then you can store a list of User objects instead
List<User> users = new LinkedList<User>();
You create your user object and populate it from the input you get, e.g.,
User user = new User();
String surname = JOptionPane.showInputDialog("...");
user.setSurname(surname);
users.add(user);
First create DVD object as below...
class DVD {
private int dvdId;
.
.
.
.
//now set getter setters
public void setdvdId(int dvdId) {
this.dvdId = dvdId
}
public int getdvdId() {
return dvdId;
}
// similarly for all field
}
Then use DVD object in arraylist as below
class MyProgram {
public static void main (String args[]) {
List<DVD> arrayList = new ArrayList<DVD>();
DVD myDVD = new DVD();
myDVD.setdvdId(Integer.parseInt(JOPtionPane.showInputDialog("Enter ID")));
// similarly add other
.
.
.
.
.
arrayList.add(myDVD)
// similarly add other
}
}
Good Luck!!!
Why don't you create a class Dvd containing all the fields that you need and store this in the ArrayList?
You shoul definitely create class for these variables, let's say DVD, then you can use it in your code like
List<DVD> arrayList = new ArrayList<DVD>(); //always use a raw types (List)
DVD dvd = new DVD();
dvd.setId(JOPtionPane.showInputDialog("Enter ID");
//and so on, when you finish, just put the object in the array
arrayList.add(dvd);
And your DVD object should override the hashCode and equals method, so you can efectivelly search DVD objects in your ArrayList
Crate a class with all the variables you need and crate objects for each your and put them into the ArrayList. I think it solves your problem.
Task at hand:Consider a class ratingScore that represents a numeric rating for some thing such as a move. Attributes: A description of what is being rated, The maximum possible rating, rating.
It will have methods to: get rating from ta user, Return the maximum rating posisble, return the rating, return a string showing the rating in a format suitable for display.
a. write a method heading for each method
b. write pre and post conditions for each method
c. write some java statements to test the class
d. implement the class.
I think i did what i was supposed to do, but it is a method and i am not sure that i put enough room for it to be changed much, this is what i have so far.
import java.util.*;
public class MovieRating
{
// instance variables
private String description = " A movie that shows how racism affect our lives and choices";
private int maxRating = 10;
private int rating;
// methods
//precondition: Must have maxRating, rating and description before you post it back to the user.
//rating between 1 and 10, maxRating is set to 10, description of a movie
public void writeOutput()
{
System.out.println("The max rating is: " + maxRating );
System.out.println("Your rating is: " + rating );
System.out.println("The rating for" + description + " is " + rating);
System.out.println("while the max rating was " + maxRating);
}
// PostCondition: Will write maxRating, rating and description to the user.
//Precondition: description, enter the rating
public void readInput()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What would you rate the movie \"American History x\" out of ten");
System.out.println(description);
rating = keyboard.nextInt();
}
//postcondition: rating will be set to user's input for the movie American History x.
}
This is my Tester program.. not much so far
public class MovieRatingTester
{
public static void main(String[] args)
{
//object of the class MovieRating
MovieRating rating1 = new MovieRating();
rating1.readInput();
rating1.writeOutput();
}
}
SO did i cover what was told to cover? i think i did but i think i did it the wrong way, let me know please.
Ok, my point of view is:
Your class, MovieRating is missing some basic elements of OOP, and that is what I think you suppose to learn in this homework.
The first element missing is a constructor method, what you did is automatically assigning each new MovieRating the same description. The job of the constructor function is giving a unique values to the Object when it first built in the system.
The constructor method is special, it is public and has the exact same name is the class, as we said, in this method you suppose to assign values to your object variables.
the second thing will be to put getters/setters, these are methods who has access to your private values and will be used to assign/get the values from them. Note the use of them in the code:
import java.util.*;
public class MovieRating
{
// instance variables
private String description;
private int maxRating;
private int rating;
/*This is the constructor
Note the use of .this - the expression is used to call the class form withing
itself*/
public MovieRating(String description, int maxRating, int rating) {
this.setDescription(description);
this.setMaxRating(maxRating);
this.setRating(rating);
}
/*These are the getters and setters - get is used for getting the value
and set is used for assigning a value to it*/
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getMaxRating() {
return maxRating;
}
public void setMaxRating(int maxRating) {
this.maxRating = maxRating;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
//This is a method for the printing commands - notice the use of the get methods//
public void printRatings()
{
System.out.println("The max rating is: " + this.getMaxRating() );
System.out.println("Your rating is: " + this.getRating() );
System.out.println("The rating for" + this.getDescription() + " is " +
this.getRating());
System.out.println("while the max rating was " + this.getMaxRating();
}
// PostCondition: Will write maxRating, rating and description to the user.
/*Precondition: description, enter the rating
Note the use of this.setRating()*/
public void readInput()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What would you rate the movie \"American History x\" out of ten");
System.out.println(description);
this.setRating(keyboard.nextInt());
}
//postcondition: rating will be set to user's input for the movie American History x.
}
Using the constructor, you can create a different rating from your tester program
MovieRating rating1 = new MovieRating("description 1", 10, 5);
MovieRating rating2 = new MovieRating("description 2", 9, 7);
You should not ask / print the data from the Ratings class. These ratings can come from user input, but also from database, web, etc.
1 Add getters and setters for properties of MovieRating
2 Pass the read and write methods to the main. Something like
System.out.println("The rating for the movie |" + rating1.getTitle() + "| is " + rating1.getRating());
3 You are not aggregating ratings to a movie. You can't have two rating to the same movie (v.g., by different users) together. Convert the rating attribute into a Vector to solve it. Change setRating for addRating
There are many other things, but obviously this is a starters exercise and I do not want you to get confused. Work on these issues and check with your teacher.
Java (and OO in general) is all about abstractions. You want to keep your objects as general as possible so that you extend your programs functionality without modifying existing code. This may be beyond what your professor was looking for but here are my suggestions:
1) Rating - separate this into its own class
Again, the rating is totally separate from the movie - songs can have ratings, tv shows can have ratings. Today ratings can be 1-10, tomorrow ratings can up thumbs up or thumbs down, etc. A Movie "has a" rating. Let Rating decide how to prompt the user and how to display itself.
2) Now that you have a separate Movie class, I would take away the hard-coded title, description in my Movie class (this will let me create many movies and rate them).
Then I would eliminate System.out.println in writeOutput method (you can pass in the OutputStream to the function)
By hard-coding in System.in you are forcing implementation. What if tomorrow your professor says "now, instead of printing to the console, print to a file or a database"? You have to modify the code. Actually, instead of writeOutput, I would override the toString method that all Objects have and then just call System.in(movie.toString()) in main.
3) Your test method doesn't "test" anything - it is just executing a statement. Typically a test method will simulate input, execute the statements, and check for the proper state at the end. A good way to signal that the state is improper (if your test fails, like maybe your Movie Rating is -1), then you throw an exception.
4) This is un-OO related and just a preference, but I would put both Pre and Post conditions before the methods. This just makes it easier to find in my opinion.
The idea of OO is that you separate responsibilities/concerns into separate classes. Each class is responsible for itself. This helps to keep your code more flexible and maintainable. Good luck on the assignment!