Object that contains ArrayList - java

I am doing a program to sell games. Now in my code it will show only the last review the customer writes, but instead I would like it to contain a list of all reviews the game got. I was thinking if it would be possible to have an ArrayList as a variable instead of the String review. Here is an example of how it looks like now.
public class Game {
private String gameName;
private int gamePrice;
private String gameReviews;
public Game(String gameName, int gamePrice, String gameReviews) {
this.gameName = gameName;
this.gamePrice = gamePrice;
this.gameReviews = gameReviews;
}
}
and then if I want to create an object how it would look like to replace the old one I had?
public class Games {
public static void main(String[] args) {
String gameN = "Name";
int gameP = 10;
String gameR = "Review";
Game game = new Game(gameN, gameP,gameR);
}
}

It is possible to use ArrayList instead of String.
import java.util.ArrayList;
class Game {
private String gameName;
private int gamePrice;
private ArrayList<String> gameReviews;
public Game(String gameName, int gamePrice, ArrayList<String> gameReviews) {
this.gameName = gameName;
this.gamePrice = gamePrice;
this.gameReviews = gameReviews;
}
public static void main(String[] args) {
String gameN = "Name";
int gameP = 10;
ArrayList<String> gameReviews = new ArrayList<String>();
gameReviews.add("Review 1");
gameReviews.add("Review 2");
gameReviews.add("Review 3");
gameReviews.add("Review 4");
Game game = new Game(gameN, gameP,gameReviews);
}
}

If the relationship between your game and the reviews is one-to-many, the data type of your reviews can be List<String>
public class Game {
private String gameName;
private int gamePrice;
private List<String> gameReviews;
public Game(String gameName, int gamePrice, List<String> gameReviews) {
this.gameName = gameName;
this.gamePrice = gamePrice;
this.gameReviews = gameReviews;
}
public Game(String gameName, int gamePrice) {
this.gameName = gameName;
this.gamePrice = gamePrice;
this.gameReviews = new ArrayList<>();
}
public void addGameReview (String gameReview) {
this.gameReviews.add(gameReview);
}
}
Then if you have the list of reviews at initialization you'd just pass it into the constructor:
List<String> reviews = new ArrayList<>();
Game game = new Game(gameN, gameP, reviews);
Otherwise, you could have a constructor that initializes gameReviews to an empty ArrayList, and add the review after the initialization
Game game = new Game(gameN, gameP);
game.addGameReview("This is a review of Game ...");

Related

How can i put an Arraylist into Arraylist

i have an exercise which i must write a programm in which i manage the timetable of trains.I write all the programm put i can not write the main class, because i must make an Arraylist with 3 passengers and i dont know what i must put in the blank
Code:
public class Route {
private int id;
private int aeroplane;
private String departure;
private String arrival;
private ArrayList<Ticket> Tickets = new ArrayList<>() ;
public Route(){
id = 0 ;
aeroplane = 0 ;
departure = " ";
arrival = " ";
Tickets = new ArrayList<>();
}
public Route(int ID, int aerop, String depar,String arriv,ArrayList<Ticket> tick ){
id=ID;
aeroplane=aerop;
departure=depar;
arrival=arriv;
Tickets=tick;
}
public static void main(String[] args) {
ArrayList <Train> train=new ArrayList<>();
Route d1= new Route(0051,50,"Greece","Italy",);// what i have to write in the last blank?
}}
I suppose you have those three classes:
Train
Ticket - which is valid for multiple trains
Route - which could contain multiple Tickets
Then you should model your Route like that:
public class Route {
private final int id;
private final int aeroplane;
private final String departure;
private final String arrival;
private final List<Ticket> tickets;
public Route(int id, int aeroplane, String departure, String arrival, List<Ticket> tickets) {
this.id = id;
this.aeroplane = aeroplane;
this.departure = departure;
this.arrival = arrival;
this.tickets = tickets;
}
}
Your route class does not have, and should not have a list of lists of trains. It is perfectly fine, that you have it has a list of tickets.
To the question of how to add the list of Trains to the Route instantiation, you should create a ticket first, or multiple if you like.
public static void main(String[] args) {
// create trains
Train train1 = new Train(1202, "Piraeus", "Athens");
Train train2 = new Train(1302, "Athens", "Thessaloniki");
Train train3 = new Train(1502, "Thessaloniki", "Rome");
// create ticket(s)
Ticket ticket = new Ticket(95, List.of(train1, train2, train3));
// create route and pass tickets
Route myRoute = new Route(0051, 50, "Greece", "Italy", List.of(ticket));
}
To create the lists here I used the factory method java.util.List.of (available since Java 9). Your route class is also a good candidate for a record (since Java 18). As an record it would look like:
public record RouteRecord(int id, int aeroplane, String departure, String arrival, List<Ticket> tickets) {}
Also, think about the concept of immutability.
In your main method ( it's not a class ) :
List<Ticket> tickets = new ArrayList<>();
tickets.add( new Ticket());
Route d1 = new Route(0051,50,"Greece","Italy",tickets);
and as it was mentined before you need to define a constructor :
public Route(int id, int aeroplane, String departure, String arrival, List<Ticket> tickets ){
this.id = id;
this.aeroplane = aeroplane;
this.departure = departure;
this.arrival = arrival;
this.Tickets = tickets;
}

i need help seperate this main method to a class

I have this movie ticket program, which I want to have a class so it becomes a main method and a class and it's aching my mind .
import java.util.Scanner;
public class MovieTicket {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String[] movielist ={"1) Shutter Island","2) Devil's Advocate","3) Pulp Fiction","4) Resvouar Dogs"};
Ticket obj=new Ticket();
System.out.println("Welcome to Vox Cinemas");
System.out.println("Please ,Selcet a movie please");
for (int i =0; i<movielist.length;i++){
System.out.println(movielist[i]);
}
int number = sc.nextInt();
System.out.println("The movie you selected is:"+" "+movielist[number-1]);
System.out.println("How many seats would you lie:");
String seats = sc.next();
System.out.println("You've selected:"+seats+"Seats");
}
}
You need to create separate classes for Theatre, Movie, Ticket etc.
Something like below.
class Movie{
private String name;
private int runtime;
//add other fields like producer/actors/genre
public Movie(String name, int runtime) {
this.name = name;
this.runtime = runtime;
}
public String getName() {
return name;
}
public int getRuntime() {
return runtime;
}
}
class Ticket{
private int number;
private Movie movie;
private String screen; //Screen 1
private String seat; //A14
public Ticket(int number, Movie movie, String screen, String seat) {
//.. initiate variables here.
}
//write getters here
}
class VoxCinema{
private List<Movie> movies = new ArrayList<>();
private String address;
//theater details like name/timings etc.
public VoxCinema() {
}
public void addMovie(Movie movie) {
this.movies.add(movie);
}
public List<Movie> getAllMovies() {
return this.movies;
}
//write getters and setters
}
Then use them in your application like this:
public class TicketBookingApplication {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
VoxCinema vc = new VoxCinema();
vc.addMovie(new Movie("Shutter Island", 130));
vc.addMovie(new Movie("Devil's Advocate", 180));
/// add all movies
System.out.println("Welcome to Vox Cinemas");
System.out.println("Please ,Selcet a movie please");
List<Movie> movies = vc.getAllMovies();
for (int i = 0; i < movies.size(); i++) {
System.out.println(i + ") " + movies.get(i).getName());
}
int number = sc.nextInt();
Movie selectedMovie = movies.get(number);
System.out.println("The movie you selected is: " + selectedMovie.getName());
System.out.println("How many seats would you lie:");
String seats = sc.next();
System.out.println("You've selected:" + seats + "Seats");
// create tickets
Ticket t = new Ticket(3341, selectedMovie, "Screen 4", "D15");
//store tickets in VoxCinema object
}
}
Implement remaining parts or modify code as per your needs.

My array members are null even though they are initialized

So I'm trying to access members inside my relation array, once it has been initialized. However it does not let me do so. What am I doing wrong?
public class FamilyRelations {
private Relationship [] relation;
public static void main(String[] args) {
FamilyRelations family = new FamilyRelations();
Scanner scanner = new Scanner(test);
family.run(scanner);
}
private void run(Scanner scanner) {
noOfRelations = 3;
relation= new Relationship [3];
System.out.println(relation[0].child); // Why does this raise nullpointerexception?
// Here I want to do relation[0].father = "John"; for example
}
public class Relationship {
public String child;
public String father;
public String mother;
public Relationship() {
this.child = "hej";
this.father = "father";
// this.mother = mother;
}

How to call a string array into a method

I have defined 3 methods in which there are String[] as parameters. I would like to set these ones from another function, with some strings, and printing each one.
When I try to call these methods from another function(the start() function), to set the values of String[] parameters Eclipse says:
Type mismatch: cannot convert from String
to String[]
public class logistics2 {
private static String plane;
private static String truck;
private static String airport[];
private static String loc[];
private static String city[];
private static String pack[];
public static void at_obj_place(String object, String[] place) {
object = truck;
object = plane;
place = loc;
place = city;
place = airport;
return;
}
public static void in_pk_vehicle(String[] Pack, String vehicle) {
Pack = pack;
vehicle = truck;
vehicle = plane;
return;
}
public static void in_city(String[] place, String[] City ) {
place = loc;
City = city;
return;
}
public static void start() {
// HERE I RECEIVE THE ERROR MESSAGE
in_city(airport = "cdg", city = "paris");
in_city(airport = "lhr", city = "london");
in_city(loc = "north", city = "paris");
in_city(loc = "south",city = "paris");
at_obj_place(plane = "plane", airport = "lhr");
at_obj_place(truck = "truck", airport = "cdg");
at_obj_place(pack1 = "p1", airport = "lhr");
at_obj_place(pack2 = "p2", airport = "lhr");
for(int i = 0; i < airport[].length(); ) {
System.out.println(airport + " " + city);
}
return;
I would like to print each of the values that I have set with the for condition, based on the count of the values number that I have inserted in the String[]
In all the methods you have to passed strings you have to pass array of strings. Like this for all arrays:
airport[0] = "cdg";
airport[1] = "lhr";
city[0] = "paris";
city[1] = "london";
then pass this to methods like:
in_city(airport,city);
And in for loop you have to mention only array name like airport not airport[] and add increment for i.

Error accessing variable of a nested class

I desperately need help. I have two classes.
One is a PatientRecord with nested classes in it.
The other is a PatientGenerator which fills a database with PatientRecords by generating random data
for each field of the PatientRecord.
My problem is that I can't access the variables of some of the nested classes but I can access others. (At least it compiles for some and fails with an error for others.)
error: cannot find symbol
temp.fname = getRFirstName();
symbol: variable fname
location: variable temp of type PatientRecord.Visitor
Here is the failing calls
private ArrayList<PatientRecord.Visitor> generateVisitors(PatientRecord p) {
int payments = rnd.nextInt(10);
ArrayList<PatientRecord.Visitor> array = new ArrayList<PatientRecord.Visitor>();
for (int i = 0; i < payments; i++) {
PatientRecord.Visitor temp = p.new Visitor();
temp.fname = getRFirstName();
temp.lname = getRLastName();
temp.relation = relations[rnd.nextInt(relations.length)];
array.add(temp);
}
return array;
}
and here is part of the class with nested class Visitor in it.
public class PatientRecord implements Serializable{
public int pId;
public String FirstName;
public String MiddleName;
public String LastName;
public boolean gender;
public Location location;
public ArrayList visitors;
public ArrayList emergencyContacts;
public DateTime discharge;
public Admission admission;
public String primaryDoctor;
public ArrayList procedures;
public ArrayList prescriptions;
public ArrayList nurseNotes;
public ArrayList doctorNotes;
public InsurancePolicy insurancePolicy;
public ArrayList billing; // Arraylist of payments
public PatientRecord() {
init();
}
public PatientRecord(int id) {
pId = id;
init();
}
private void init() {
visitors = new ArrayList<Visitor>();
emergencyContacts = new ArrayList<Contact>();
location = new Location();
discharge = new DateTime();
admission = new Admission();
procedures = new ArrayList<Procedure>();
prescriptions = new ArrayList<Prescription>();
nurseNotes = new ArrayList<Note>();
doctorNotes = new ArrayList<Note>();
billing = new ArrayList<Payment>();
insurancePolicy = new InsurancePolicy();
}
public class Visitor {
public String fname;
public String lname;
public String relation;
public Visitor() {
}
}
I have no compilation errors (after having removed some of the code):
public class PatientRecord
{
public int pId;
public String FirstName;
public String MiddleName;
public String LastName;
public boolean gender;
public ArrayList visitors;
public ArrayList emergencyContacts;
public String primaryDoctor;
public ArrayList procedures;
public ArrayList prescriptions;
public ArrayList nurseNotes;
public ArrayList doctorNotes;
public ArrayList billing; // Arraylist of payments
public PatientRecord() {
init();
}
public PatientRecord(int id) {
pId = id;
init();
}
private void init() {
visitors = new ArrayList<Visitor>();
}
public class Visitor
{
public String fname;
public String lname;
public String relation;
}
public class PatientGenerator
{
public ArrayList<PatientRecord.Visitor> generateVisitors(PatientRecord p) {
//int payments = rnd.nextInt(10);
ArrayList<PatientRecord.Visitor> array = new ArrayList<PatientRecord.Visitor>();
for (int i = 0; i < 10; i++) {
PatientRecord.Visitor temp = p.new Visitor();
temp.fname = "first";
temp.lname = "last";
temp.relation = "brother";
array.add(temp);
}
return array;
}
}
public static void main(String[] args)
{
PatientRecord t = new PatientRecord();
PatientGenerator c = t.new PatientGenerator();
c.generateVisitors(t);
}
}
Does your code look similar to this?

Categories

Resources