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.
Related
I have an arraylist called cities with objects City from another class, and this object contains both the name of said city but also population. In one method I wanna sum all city populations, aka get the population of the country, however I'm getting an exception in .parseLong method the way I'm doing it. In another one, I wanna check what city has the largest population, but I'm not getting anything when I print and don't know how to fix it. Basically I don't know how to get the value of the objects inside the arraylist. Commented where I have issues for better understanding. Help's appreciated!
public class Country {
private String name;
private City capital;
private int pop;
private ArrayList<City> cities;
public Country(String name, Cidade capital, int pop) {
this.name = name;
this.capital = capital;
this.pop = pop;
cities = new ArrayList<>();
cities.add(capital);
}
public long getTotalPop(){
String c = null;
Iterator<City> iter = cities.iterator();
while(iter.hasNext()){
c += iter.next();
long s = Long.parseLong(c); //giving exception here
System.out.println(s);
return s;
}
return 0;
}
public City getLargest(){
for(City city: cities){
if(city.getPop()>city.getPop()){ //method is fine but if is very wrong since am not sure what to compare to
return city;
}
}
return null;
}
}
public class City {
private String name;
private int pop;
public City(String name) {
this.name = name;
}
public City(String name, int pop) {
this.name = nome;
this.pop = pop;
}
public String getName() {
return name;
}
public int getPop() {
return pop;
}
public void setName(String name) {
this.name = name;
}
public void setPop(int pop) {
this.pop = pop;
}
}
About your Methode getTotalPop()
c should be a long variable and in initialized to 0 because now you are trying to increment a string which is impossible.
you are iterating about a list of cities so iter.next() will give you a city but you want the population of this city so call c += iter.next().getPop();
You don't have to use an iterator. It is okay but you won't get a benefit in this case. My recommendation use a enhanced for/foreach loop.
So use this(iterator):
public long getTotalPop(){
long result = 0;
Iterator<City> iter = cities.iterator();
while(iter.hasNext()){
result += iter.next().getPop();
}
return result;
}
or this(enhanced for/foreach loop):
public long getTotalPop(){
long result = 0;
for (City city : cities) {
result += city.getPop();
}
return result;
}
About your Methode getLargest()
There are some ways to do the job you could use an variable largest pop initialized to 0 and compare each City population with this variable and set it to the pop if it is greater. Or set your pop of the first City as the value to be compared.
With first City:
public City getLargest() {
if (!cities.isEmpty()) {
City largest = cities.get(0);
for (int i = 1; i < cities.size(); i++) {
City city = cities.get(i);
if (largest.getPop() < city.getPop()) {
largest = city;
}
}
return largest;
}
return null;
}
Furthermore because you don't initialize cities in the construtor other than to the new ArrayList don't do that in the constructor but like this:
private List<City> cities = new ArrayList<>();
public Country(String name, City capital, int pop) {
this.name = name;
this.capital = capital;
this.pop = pop;
this.cities.add(capital);
}
At last why is the pop of the country not the same as the pop of all of the cities it has? It would make totaly sense to initialize pop to the result of getTotalPop()
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)
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
So I want to use for-each loops to search in my arraylist in order to find the capital of the country that's typed in, also the search isn't case sensitive. The arraylist name in my other class that is ElementsList. Below is the code from the Country() class that includes the capital:
import java.text.*;
/**
* Write a description of class Country here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class Country
{
private String nCountry;
private String Cont;
private int Area;
private double populationNum;
private double GDP;
private String Capital;
public Country (){
nCountry = "Default";
}
public Country (String name, String continent, int area, double population,
double gdp, String capital){
nCountry = name;
Cont = continent;
Area = area;
populationNum = population;
GDP = gdp;
Capital = capital;
}
public String getCountry(){
return nCountry;
}
public String getCapital(){
return Capital;
}
public void setCountry(String name){
nCountry = name;
}
public void setCapital(String capital){
Capital = capital;
}
}
The thing I'm having trouble with is creating the for-each loop to search for the capital of the country that is being used. It's not much but this is what I've got so far:
public String searchForCapital(String countryName){
Country cap = new Country();
cap = null;
for(Country c : ElementsList){
if(c.getCountry().equals(countryName)){
}
your for each is right. here is the full function to search for capital,Note that you have to have elementsList array list of Country objects
public String searchForCapital(String countryName) {
for (Country c : elementsList) {
if (c.getCountry().equalsIgnoreCase(countryName)) {
return c.getCapital();
}
}
return null;
}
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.