How can I create a new object every time my program loops? - java

How my program is set up is that my code runs and allows the user to create a new movie object which is then stored to the constructor. It then gives the option to create a new movie which is then stored in the same movie object, which ultimately overwrites the previous movie object that was created. Many implementation go about putting the object creation in a loop, but this asks for all the multiple values to be stored into multiple objects all at once, I'm not looking to do that. I'm not sure how to go about solving this.
Here's my code
Movie class
public class Movie {
private int id;
private String name;
private String description;
private String[] genre;
private String[] actors;
private String[] language;
private String countryOfOrigin;
private Map<String, Integer> ratings;
Movie() {
}
//Constructor
public Movie(int id, String name, String description, String[] genre, String[] actors, String[] language, String countryOfOrigin, Map<String, Integer> ratings) {
this.id = id;
this.name = name;
this.description = description;
this.genre = genre;
this.actors = actors;
this.language = language;
this.countryOfOrigin = countryOfOrigin;
this.ratings = ratings;
}
//setters
public void setid(int id) {
this.id = id;
}
public void setname(String name) {
this.name = name;
}
//getters
public int getId() {
return id;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "\nMovie Id: " + id + " \nMovie Name: " + name + "\nMovie Description: " + description + "\nMovie Genre(s): " + Arrays.toString(genre) + "\nMovie Actor(s): " + Arrays.toString(actors) + "\nMovie Language(s): " + Arrays.toString(language) + "\nCountry of Origin: " + countryOfOrigin + "\nRatings: " + ratings +"";
}
}
Main class
public class Main {
// --- Private global scanner initialization --- //
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws Exception {
while (loopAgain) {
Random rand = new Random();
int id = rand.nextInt(MAX);
System.out.println("\nCreate Poll");
System.out.println("\nEnter the Movie Name: ");
String name = input.nextLine();
Movie movie1 = new Movie(id, name, description, genre, actors, language, countryOfOrigin, mapRatings);
System.out.println("Create new movie? (y/n): ");
String answer = input.nextLine();
if (answer.equals("y") || answer.equals("Y")) {
loopAgain = true;
}
}
}
}

You can store the movie objects in some kind of container after you create them. So you can use an ArrayList for example
ArrayList<Movie> movies= new ArrayList<Movie>();.
You can put this above your while loop. Then after you create the object you can add it into the container such as movies.add(movie1) you can put this right under where you called the constructor. Later on to access the object, you can use movies.get(index)

Related

Print specific element of an arraylist in Java based on a given parameter

There's this task I'm working on, in which I have to make an arraylist based on an Author class, which has as its properties: ID, author's name, book and nationality. This aside, I had to make another class, which receives as a parameter the ID, and returns the corresponding author's info. My problem is that I wrote the code, but no matter what ID my input receives, it always retrieves the same author's information. Could anyone help me on this?
Author.java
public class Author {
private int id;
private String name;
private string book;
private string country;
public Author(int id, String name, String book, String country) {
this.id = id;
this.name = name;
this.book = book;
this.country = country;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getBook() {
return book;
}
public int getCountry() {
return country;
}
#Override
public String toString() {
return "Id: " + this.id + ", Name: " + this.name + ", Book:" + this.book + ", Country:" + this.country;
}
}
GetAuthor.java (class used to retrieve Author's info based on the ID)
public class GetAuthor {
public Author returnAuthor(int id, ArrayList<Author> list) {
Author author = null;
id = 0;
for (int i = 0 ; i < list.size() ; i++) {
if(author == null || author(i).getId() == id) {
author = list.get(i);
id = list.get(i).getId();
}
}
return author;
}
}
Main.java
public class Main {
public static void main(String[] args) {
Author w1 = new Author(1, "Franz Kafka", " The Metamorphosis", "Austria");
Author w2 = new Author(2, "Neil Gaiman", "Sandman", "England");
Author w3 = new Author(3, "Jack Kerouac", "On The Road", "USA");
ArrayList<Author> authors = new ArrayList<>();
authors.add(w1);
authors.add(w2);
authors.add(w3);
for(int i = 0 ; i < authors.size() ; i++){
System.out.println(authors.get(i));
}
Scanner scan = new Scanner(System.in);
System.out.print("Enter the author's ID: ");
int num = scan.nextInt();
GetAuthor theAuthor = new GetAuthor();
Author author = theAuthor.returnAuthor(num,authors);
System.out.println(author);
}
}
public static Author returnAuthor(int id, ArrayList list) {
return list.stream().filter(auth -> auth.getId()==id).findFirst().orElse(null);
}
id = 0;
Here you override the passed-in value for id; that's probably why you always get the same answer.
if(author == null || author(i).getId() == id) {
This shouldn't even compile; author is not a method (in your example).

Java how can I make a book class that can have one or more authors

So I'm practictising Object oriented programming and I'm trying to make a Book class that can have multiple authors but I don't know how to do it.
This is the UML of the excerise:
This is my author class which works fine:
public class Author {
//attributen van de class auteur
private String name;
private String email;
private char gender;
//constructor
public Author (String name, String email, char gender){
this.name = name;
this.email = email;
this.gender= gender;
}
//methodes
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public char getGender(){
return gender;
}
//methode om gegevens van autheur opbject op te halen
public String toString(){
return "Author[name = " + name + ", email = " + email + ", gender = " + gender + "]";
}
}
And here is the Book class that I tried to make:
public class Book {
//attributes
private String name;
private Author authors [] = new Author[2];
private double price;
private int qty = 0;
public Book(String name, Author authors[], double price, int qty) {
this.name = name;
authors[0] = new Author("Tan Ah Teck", "AhTeck#somewhere.com", 'm');
authors[1] = new Author("Paul Tan", "Paul#nowhere.com", 'm');
this.price = price;
this.qty = qty;
}
public String getName() {
return name;
}
public Author getAuthors() {
return authors[authors.length];
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public String toString() {
return "Book [name = " + name + " authors = " + authors[0] + " email = " + authors[0].getEmail() + " price = " + price + " qty = " + qty + "]";
}
//methodes om gegevens van de autheur op te halen
public String getAuthorNames() {
return authors[].getName();
}
public String getAuthorEmails() {
return authors[].getEmail();
}
public char getAuthorGenders() {
return authors[].getGender();
}
}
So when I try to make an object of a book in my main.java the constructor of the book class is not working.
Also at this function : public Author getAuthors() {
it says: Array index is out of bounds.
Also at the methods to get the author names, emails and genders it says: Unknown class authors[].
How can I modify this book class so a book can have one or more authors? (the Book class did work when a book only could have 1 author, but now I'm trying to change it so a book can have more authors)
Any kind of help is appreciated!
When you don't provide this keyword for authors within your constructor, the code works with your constructor parameter not with your class variable, therefore you encounter that problem.
try removing the authors from constructor like this:
public Book(String name, double price, int qty)
it says: Array index is out of bounds
First, it cannot say that with the given code, because it doesn't compile with the last three methods.
And well, authors.length == 2, and your array only has indicies 0 and 1
If you want to actually "get the authors", you want to return the array, not a specific one
public Author[] getAuthors() {
return authors;
}
And if you did want to get one, then add the index.
It's also good habit to add boundary checking
public Author getAuthor(int index) {
return (index < 0 || index >= authors.length) ? null : authors[index];
}
However, with these fixes, you might see null now because you actually have two list; the one you will pass to new Book(), and the field within the instance of that object.
Rather, you will want to do
private Authors[] authors;
public Book(String name, Author authors[], double price, int qty) {
this.name = name;
this.authors = authors;
And in the main method create the authors
Author[] authors = new Author[] {
new Author("Tan Ah Teck", "AhTeck#somewhere.com", 'm'),
new Author("Paul Tan", "Paul#nowhere.com", 'm')
};
Book b = new Book("name", authors, ...);
System.out.println(Arrays.toString(b.getAuthors()));
Also at the methods to get the author names, emails and genders it says: Unknown class authors[]
Because authors[].blah is not valid syntax. You need to loop over each of the array values to get the respective fields.
I would suggest Arrays.stream methods and StringJoiner for handling this

Java Eclipse: My code's output is skipping a line and I don't know why [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
The title says it all. This is a basic Customer class that the user inputs their name/age/street address/city/state/zip code and then the program formats the input and returns it to the user. When I run this class it skips over the 'Street Address' and goes straight to 'City' and thus I can't get it to let me input my street address.
I've looked at a fairly similar issue in this thread here: Java is skipping a line (Strings in a Scanner ??)
However I haven't derived anything from that that has helped me solve this issue. I'm sure its extremely basic but I'm just unable to catch it and don't have much time to work on this today, so any tips/help are appreciated!
public class Customer {
String name;
String streetAddress;
String city;
String state;
String zip;
int age;
//default constructor
public Customer() {
name = "Unknown";
streetAddress = "Unknown";
city = "Unknown";
state = "Unknown";
zip = "Unknown";
age = 0;
}
//constructor to accept values for the above attributes
public Customer(String n, String sAdd, String c, String st8, String z, int a) {
name = n;
streetAddress = sAdd;
city = c;
state = st8;
zip = z;
age = a;
}
//getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String displayAddress() { //returns a string with the complete formatted address
String showAddress;
showAddress = ("\nStreet Address: " + streetAddress + "\nCity: " + city + "\nState: " + state + "\nZip Code: " + zip);
return showAddress;
}
public String displayAddressLabel() { //returns a string with the customers name/age
String nameAgeAddress;
nameAgeAddress = ("Name: " + name + "\nAge: " + age);
return nameAgeAddress;
}
//main method
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//creating an object of the Customer class
Customer actualCustomer = new Customer();
//getting info for displayAddressLabel() and displayAddress
System.out.println("Enter your name: ");
actualCustomer.setName(scan.nextLine());
System.out.println("Enter your age: ");
actualCustomer.setAge(scan.nextInt());
//issue is here
System.out.println("Enter your street address: ");
actualCustomer.setStreetAddress(scan.nextLine());
System.out.println("Enter the city you live in: ");
actualCustomer.setCity(scan.nextLine());
System.out.println("Enter the state you live in: ");
actualCustomer.setState(scan.nextLine());
System.out.println("Enter your zip code: ");
actualCustomer.setZip(scan.nextLine());
System.out.println(actualCustomer.displayAddressLabel());
System.out.println(actualCustomer.displayAddress());
}
}
After this line:
actualCustomer.setAge(scan.nextInt());
you should call:
scan.nextLine();
because after scan.nextInt() there is a new line character left to be read (after inputting int you press Enter to confirm your input and you're missing to read it from your Scanner). Instead of writing these two lines:
actualCustomer.setAge(scan.nextInt());
scan.nextLine();
You might want to change it to:
actualCustomer.setAge(Integer.parseInt(scan.nextLine()));
It will get rid of new line character.

Filling array with next empty space?

Here are my two classes Country and Countries. I am doing questions from online as extra practice.
I need to:
-Add a method to Countries - addCountry(String name, String capital, int population - Which fills in the element by nextFreeCountry and increments nextFreeCountry
Can somebody provide some help? I am struggling to understand how to fill in the element by nextFreeCountry.
Country:
public class Country {
private String name;
private String capital;
private int population;
Constructor to add the name capital and population
public Country(String name, String capital, int population) {
this.name = name;
this.capital = capital;
this.population = population;
}
Get name method
public String getName() {
return name;
}
public String getCapital() {
return capital;
}
public int getPopulation() {
return population;
}
public String toString() {
return "Name = " + getName() + " Capital = " + getCapital() + " Population = " + getPopulation();
}
}
Countries:
class Countries {
Creating an array of Country called countries
private Country[] countries;
private int nextFreeCountry = 0;
Setting the size for the array
public Countries(int size) {
countries = new Country[size];
}
addCountry method
public void addCountry(String name, String capital, int population) {
countries[nextFreeCountry] =
nextFreeCountry++;
}
}
As countries array hold Country objects, so create a new object and put it in array. Something like this:
public void addCountry(String name, String capital, int population) {
countries[nextFreeCountry] = new Country(name,capital,population);
nextFreeCountry++;
}
You have to add a new country to the array which you are not doing at the moment. Like so:
public void addCountry(String name, String capital, int population) {
countries[nextFreeCountry] = new Country(name, capital, population);
nextFreeCountry++;
}
Alternatively just pass a Country to the method like this:
public void addCountry(Country country) {
countries[nextFreeCountry] = country;
nextFreeCountry++;
}
You may also be better off using an ArrayList rather than an array so you dont have to worry about the array index being out of bounds etc.

Which utility class can be used to store and apply sort in Java

I'm a bit confused that which of the utility classes can be used for this type of problem:
I have a file Movies.txt containing info like: Id, Name, Director, Rating. Rating may or may not be present.
Sample:
1,ABC,Mr. xyz,4.5
3,GHI,Mr. mno
2,DEF,Ms. stu,3
I need to read and store this file to the memory and then apply sort by rating as well as by name and then write to the file later on.
Which utility class can best help me in this situation, so that it can be an ease to do this if possible. No more files to be used.
Start by defining a Object that describes the basic properties of a "Movie". Take make your life easier, it might be a good idea to implement Comparable<Movie> directly.
public class Movie implements Comparable<Movie> {
private int id;
private String name;
private String directory;
private double rating;
public Movie(int id, String name, String directory, double rating) {
this.id = id;
this.name = name;
this.directory = directory;
this.rating = rating;
}
public int getId() {
return id;
}
public String getDirectory() {
return directory;
}
public String getName() {
return name;
}
public double getRating() {
return rating;
}
#Override
public int compareTo(Movie o) {
int diff = (int) asInt(getRating()) - asInt(o.getRating());
if (diff == 0) {
diff = getName().compareTo(name);
}
return diff;
}
protected int asInt(double value) {
String text = Double.toString(value);
text = text.replaceAll("\\.", "");
return Integer.parseInt(text);
}
#Override
public String toString() {
return getId() + ", " + getName() + ", " + getDirectory() + ", " + getRating();
}
}
Create a List to hold the incoming movies
List<Movie> movies = new ArrayList<Movie>(25);
Read the contents of the and parse each line into their separate property elements (I'll leave that you), add each newly create Movie to the list...
movies.add(new Movie(...));
Use Collections.sort(movies) to sort them...
For example...
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortExample {
public static void main(String[] args) {
List<Movie> movies = new ArrayList<Movie>(5);
movies.add(new Movie(1, "ABC", "Mr. xyz", 4.5));
movies.add(new Movie(2, "GHI", "Mr. mno", 0));
movies.add(new Movie(3, "DEF", "Ms. stu", 3));
movies.add(new Movie(4, "AT1", "Mr. T", 3));
System.out.println("Before....");
for (Movie movie : movies) {
System.out.println(movie);
}
Collections.sort(movies);
System.out.println("After....");
for (Movie movie : movies) {
System.out.println(movie);
}
}
public static class Movie implements Comparable<Movie> {
private int id;
private String name;
private String directory;
private double rating;
public Movie(int id, String name, String directory, double rating) {
this.id = id;
this.name = name;
this.directory = directory;
this.rating = rating;
}
public int getId() {
return id;
}
public String getDirectory() {
return directory;
}
public String getName() {
return name;
}
public double getRating() {
return rating;
}
#Override
public int compareTo(Movie o) {
int diff = (int) asInt(getRating()) - asInt(o.getRating());
if (diff == 0) {
diff = getName().compareTo(name);
}
return diff;
}
protected int asInt(double value) {
String text = Double.toString(value);
text = text.replaceAll("\\.", "");
return Integer.parseInt(text);
}
#Override
public String toString() {
return getId() + ", " + getName() + ", " + getDirectory() + ", " + getRating();
}
}
}
You need to read this input file one line at a time, parse each line by splitting at ',', constructing a Movie object (that you define) and adding to some kind of array / map / set. Then sort your array / map / set according to the instructions, and write out the response file.
Do some research into:
reading lines from files
parsing strings using split
lists, maps
sorting (compare)
OK, an answer has been accepted, but I have the right not to have the same opinion.
Comparable should reflect the relationship between 2 objects based on their entire state(of course, ids and other irrelevant fields are skipped). If you want to order some objects by their partial state(a few fields) you should use a Comparator.

Categories