I have a ScenarioGenerator class to generate the Scenario. And in the Audit class, I set the function to decide how many scenarios to be generated and wanted to print out the occurrence of each enum type (Gender in this case).
I've referred to Counting an Occurrence in an Array (Java)
I used the frequency method to count the occurrence, but when there are many scenarios generated, I don't know how to aggregate the data. What I've tried was:
Generate the scenarios and add each scenario in the ArrayList
For each scenario, I get the passenger ArrayList, and save their attributes in different collections.
For each collection, print out its value and the count.
I can simply do like this:
int maleCount = Collections.frequency(genderCollection, Gender.MALE);
System.out.println(Gender.MALE.toString().toLowerCase() + ":" +maleCount);
However, if I have more enums and attributes, this method becomes lengthy and inefficient. Is there any way to deal with this?
Here is part of my Audit class:
public class Audit {
private Scenario scenario = new Scenario();
private ScenarioGenerator scenarioGenerator = new ScenarioGenerator();
private Person person = new Person();
private String auditType;
private int nubmerOfSimulation;
public enum Gender {
MALE, FEMALE, UNKNOWN;
}
public Audit() {
}
// create a specific number of random scenarios
// the concept similar to gamePlayed and gameWon in the last project
public void run(int runs) {
this.nubmerOfSimulation = runs;
ArrayList<Scenario> scenarios = new ArrayList<Scenario>();//create a arrayList to store each scenario
for (int i = 0; i < runs; i++) {
Scenario singleScenario = scenarioGenerator.generate();
scenarios.add(singleScenario); // save each scenario into a scenario arrayList
}
survialCalculator(scenarios);
}
public int survialCalculator(ArrayList<Scenario> scenarios) {
//person attribute arrayList
ArrayList<Gender> genderCollection = new ArrayList<Gender>();
for (Scenario scenario : scenarios) { // for each scenario, getting its passengers and pedestrians
ArrayList<Character> passengers = scenario.getPassengers();
for (Character passenger : passengers) {
if (passenger instanceof Person) {
Gender gender = ((Person) passenger).getGender();
//System.out.println(gender);
genderCollection.add(gender);
}
}
//try to print out the elements in the collection and its frequency, but failed
for(Gender genderElement : genderCollection) {
int genderCount = Collections.frequency(genderCollection, genderElement);
System.out.println(genderElement.toString().toLowerCase()+ ":" + genderCount);
}
return 1;
}
Here is part of my ScenarioGenerator:
public class ScenarioGenerator {
private Person person = new Person();
private Random random = new Random();
private int passengerCountMinimum;
private int passengerCountMaximum;
private int pedestrianCountMininum;
private int pedestrianCountMaximum;
private ArrayList<Character> passengers = new ArrayList<Character>();
private ArrayList<Character> pedestrians = new ArrayList<Character>();
public Person getRandomPerson() {
//need age, gender, bodyType, profession, pregnancy
int age = random.nextInt(100);
int profession = random.nextInt(person.getProfessionEnumLength());
int gender = random.nextInt(person.getGenderEnumLength());
int bodyType = random.nextInt(person.getBodyTypeEnumLength());
int pregnancy = random.nextInt(2);
Person people = new Person(age,
Profession.values()[profession],
Gender.values()[gender],
BodyType.values()[bodyType],
pregnancy == 1 ? true : false);
return people;
}
public Animal getRandomAnimal() {
//species, isPet
int age = random.nextInt(100);
int gender = random.nextInt(person.getGenderEnumLength());
int bodyType = random.nextInt(person.getBodyTypeEnumLength());
boolean isPet = random.nextBoolean();
String [] species = {"cat", "dog"};
int idx = random.nextInt(species.length);
String pickSpecies = species[idx];
Animal creature = new Animal(age, Gender.values()[gender], BodyType.values()[bodyType] , pickSpecies);
creature.setIsPet(isPet);
return creature;
}
//getters and setter of min and max numbers of passengers and pedestrians
public Scenario generate() {
//random number of passengers and pedestrians with random characteristics
//randomly red light or green light
//random condition "You" in the car
//abide by the minimum and maximum counts from above setters
//get random numbers abide by the setters
int numberOfPassengers = ThreadLocalRandom.current().nextInt(getPassengerCountMin(), getPassengerCountMax()+1);
int numberOfPedestrains =ThreadLocalRandom.current().nextInt(getPedestrianCountMin(), getPedestrianCountMax()+1);
boolean legalCrossing = random.nextBoolean();
//generate the number from the total numbers of passenger and pedestrians
int numberOfPersonPassenger = ThreadLocalRandom.current().nextInt(0, numberOfPassengers+1);
int numberOfAnimalPassenger = numberOfPassengers - numberOfPersonPassenger;
int numberOfPersonPedestrian = ThreadLocalRandom.current().nextInt(0, numberOfPedestrains+1);
int numberOfAnimalPedestrian = numberOfPedestrains - numberOfPersonPedestrian;
//generate the number of person passengers
for (int i = numberOfPersonPassenger; i > 0; i--) {
Person person = getRandomPerson();
passengers.add(person);
}
//remaining of the number of passengers should be animals
//no matter it is pet of not
for (int i = numberOfAnimalPassenger; i > 0; i--) {
Animal animal = getRandomAnimal();
passengers.add(animal);
}
for (int i = numberOfPersonPedestrian; i > 0; i--) {
Person person = getRandomPerson();
pedestrians.add(person);
}
for (int i =numberOfAnimalPedestrian; i > 0; i--) {
Animal animal = getRandomAnimal();
pedestrians.add(animal);
}
Scenario scenario = new Scenario(passengers, pedestrians, legalCrossing);
return scenario;
}
Here is part of my Scenario class:
public class Scenario {
private Random random;
private ArrayList<Character> passenagers = new ArrayList<Character>();
private ArrayList<Character> pedestrians = new ArrayList<Character>();
private boolean legalCrossing;
public Scenario() {
}
public Scenario(ArrayList<Character> passengers, ArrayList<Character> pedestrians, boolean isLegalCrossing) {
this.passenagers = passengers;
this.pedestrians = pedestrians;
this.legalCrossing = isLegalCrossing;
}
//getters and setters
The main class is to call the method:
public static void main(String[] args) throws Exception {
ethicalEngine.generate();
}
public void generate() {
Audit audit = new Audit();
audit.run(5);
}
You can use groupingBy stream operation on List<Gender> to get map of all gender type with count.
Map<Gender, Long> counted = genderCollection.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
And print this way
for (Map.Entry<Gender, Long> item : counted.entrySet()) {
System.out.println(item.getKey().toString()+ ":" + item.getValue());
}
You might consider using the Guava Multiset. As Stated here this data structure is more efficent when you have more attributes to count as the access to the number lies most of the time in O(1).
Related
I would like to convert the following code from array to any other way (the most important is effective) which means that there is infinite space and I will not have to set the length of the array.
How can this be done? How can I set up an unlimited cities? using LinkedList
The idea is that it is possible to define a certain country in which certain cities are stored (the name of the city, the city center, the central bus station,... - as in the picture below) - In my code MAX_NUM_CITIES = 1000;
My Code:
public class Country {
//instance variables
private String _countryName; // name of the country
private City[] _cities; // Array of the cities
private int _noOfCities; //number of cities in a country
public void CityArray() {
_cities = new City[MAX_NUM_CITIES];
_noOfCities = 0;
}
//constants:
public final int MAX_NUM_CITIES = 1000;
/**
* Constructer for object in Country class construct Country with info accordingly
* #param countryName represents the name of country
* #param cities represents the cities array
* #param noOfCities represents the number of cities
*/
public Country(String countryName) {
this._countryName = _countryName;
this._noOfCities = _noOfCities;
City[] cities = new City[MAX_NUM_CITIES];
}
boolean addCity(java.lang.String cityName, double XcityCenter, double YcityCenter, double XStationPoint, double YStationPoint, long numOfResidents, int numOfNeighborhoods) {
if (_noOfCities <= MAX_NUM_CITIES) return false;
_cities[_noOfCities++] = new City(cityName, XcityCenter, YcityCenter, XStationPoint, YStationPoint, numOfResidents, numOfNeighborhoods);
return true;
}
public long getNumOfResidents() {
long SumOfCities = 0;
if (_noOfCities > 0) //empty Array
{
SumOfCities = _cities[0].getNumOfResidents();
for (int i = 1; i < _noOfCities; i++)
SumOfCities += _cities[i].getNumOfResidents();
} else
SumOfCities = 0;
return SumOfCities;
}
public String getCountryName() {
return this._countryName;
}
public int getNumOfCities() {
return this._noOfCities;
}
public City[] getCities() {
int noOfCities = this._noOfCities;
City[] cities = new City[noOfCities];
for (int i = 0; i < _noOfCities; i++) cities[i] = new City(this._cities[i]);
return cities;
}
public String toString() {
if (_noOfCities == 0) //empty Array
System.out.println("There are no cities in this country ");
else
for (int i = 0; i < _noOfCities; i++) _cities[i].toString();
return toString();
}
}
I would step away from arrays if the length is:
unknown
can change
I suggest using one of the different List implementations from the JDK, specifically ArrayList and LinkedList.
The first uses an internal array which may be expanded if an element is added and would lead to the array being too small (it does this all by itself, so no need to worry).
The second is a node list, which means that for every element you add, a new (internal) node object is appended to the last node.
You'd of course have to change your code for this.
Define your _cities to be a List<City>: private List<City> _cities
Initialize that with the wanted implementation in the constructor: _cities = new ArrayList<>(); or _cities = new LinkedList<>();
In your add method you can just call: _cities.add(new City(cityName, XcityCenter, YcityCenter, XStationPoint, YStationPoint, numOfResidents, numOfNeighborhoods));
In your getNumOfResidents you can use the following snippet (which uses Java streaming api introduced in java 8):
return _cities.stream()
.mapToLong(City::getNumOfResidents)
.sum();
for getCities() you'd have to change the return type to List<City> and use the following: return new ArrayList<>(_cities) or return new LinkedList<>(_cities) depending on the implementation you want to use.
I'm trying to create a FileIO where random numbers are placed into a .txt file and outputted, sorted in another .txt file. I have a bubble sort code that can sort numbers & I have another code that makes a .txt file. I'm just not sure how I'd implement these 2 together.
Here's my fileIO code:
public static void main(String[] args) {
File file = new File("test.txt");
//Writes name and age to the file
try {
PrintWriter output = new PrintWriter(file);
output.println("Rober");
output.println(27);
output.close();
} catch (IOException ex) {
System.out.printf("ERROR: %s\n", ex);
}
//Reads from the file
try {
Scanner input = new Scanner(file);
String name = input.nextLine();
int age = input.nextInt();
System.out.printf("Name: %s Age %d\n", name, age);
} catch (FileNotFoundException ex) {
System.out.printf("ERROR: %s\n", ex);
}
}
And here is my bubble sort code:
public static void main(String[] args) {
Random num = new Random();
//Creating an array for 10 integers
int [] number = new int [10];
System.out.print("Random Numbers:");
/*Display the unsorted numbers in a random order.
These numbers range from 0 to 100
*/
for (int d = 0 ; d<number.length ; d++){
/* We add a "+1" to the nextInt(100) here because then the numbers
will only range from 0 to 99.
*/
int RandomG = num.nextInt(100)+1;
number[d] = RandomG;
System.out.print(" " +RandomG);
}
//Display the sorted numbers
System.out.print("\nSorted Numbers:"+Arrays.toString(BubbleSortAsceMethod(number)));
}
public static int [] BubbleSortAsceMethod(int[] number){
int placeholder;
for(int i = 0 ; i < number.length-1 ; i++){
for ( int x = 1 ; x < number.length-i ; x++){
/*If the first number in the sequence is greater than the second
number, than save the first number of sequence in placeholder
and place the second number in the first numbers position, and
put the placeholder in the second numbers position (SWAP).
*/
/*
Since this is saying that when the first term is bigger than the
2nd term, the sequence will increase. If we flip the relational
operator, the sequence will decrease.
*/
if ( number[x-1] < number[x]){
placeholder = number[x-1];
number[x-1] = number[x];
number[x] = placeholder;
}
}
}
return number;
}
I'm kinda new to all this java stuff so please go a bit easy on me! Any help at all is appreciated :)
As the data contained in the file will consist of a pair of values: The name (String) and the age (int), you will need to retain their relationship. The best way of doing this would be to create a Class to represent the data. Eventually you want to sort the data on age using your BubbleSort method. While practically this would not be your first choice to sort data, I assume that this is a requirement. The BubbleSort method you have sorts an int[] by comparing each entry against it's immediate neighbor. With int being primitive, you can directly compare each element using the < operator.
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.age = age;
this.name = name;
}
public String getName() { return name; }
public int getAge() { return age; }
#Override
public String toString() {
return name + System.lineSeperator() + age;
}
#Override
public int compareTo(Person person) {
return this.age - person.age;
}
}
You may want to implement the Comparable interface to compare Objects; in which the interface must be implemented by Overriding the compareTo(Person person) method. You can impose sorting on age by returning the difference in age. This is not the only way you can impose the order you want; you may wish to compare directly using the getAge() of each Object or create a Comparator object.
Using the Comparable interface does allow you to make your BubbleSort class more generic, however (though the array must be of Objects that implement the interface; hence no primitive types).
public class BubbleSort {
public static <T extends Comparable> T[] BubbleSortAsceMethod(T[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int x = 1; x < array.length - i; x++) {
if (comparator.compare(array[x - 1], array[x]) < 0) {
T placeholder = array[x - 1];
array[x - 1] = array[x];
array[x] = placeholder;
}
}
}
return array;
}
}
You will notice that this sort method has some slight differences from your original, namely the BubbleSortAsceMethod method signature with the introduction of generic type parameters. Once again, this is completely optional, though this does give you the flexibility to use this method in the future for other arrays of Classes that extend the Comparable interface.
If you don't want to use generics or the Comparable interface, you will need to change the method signature and if statement.
You're method signature should instead look like public static Person[] BubbleSortAsceMethod(Person[] array) and the if statement if (array[x-1].getAge() < array[x].getAge())
This can give you an illustration of it working, though this does not consider the file io which should be simple to implement from what you have done already.
static Random random = new Random();
public static void main (String args[]) {
int size = 100;
Person[] peopleArray = new Person[size];
for (int i = 0; i < size; i++) {
String name = generateName(random.nextInt(4) + 4);
int age = random.nextInt(100);
peopleArray[i] = new Person(name, age);
}
peopleArray = BubbleSort.BubbleSortAsceMethod(peopleArray);
}
Note that this conforms, at least as much as possible, to the code you have implemented this far. If the BubbleSort and use of arrays are not critical, data structures that implement the List interface, such as ArrayList, can allow you to implement this much cleaner. This does not use the BubbleSort method at all.
public static void main (String args[]) {
int size = 100;
ArrayList<Person> people = new ArrayList<>();
for (int i = 0; i < size; i++) {
String name = generateName(random.nextInt(4) + 4);
int age = random.nextInt(100);
people.add(new Person(name, age));
}
peopleList.sort(Person::compareTo);
//or, if you don't want to implement comparable
peopleList.sort(Comparator.comparing(Person::getAge));
}
Appendix:
Used for illustrative purposes: Generates a name of a set length (randomly).
static char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
public static String generateName(int length) {
if (length > 0) {
return alphabet[random.nextInt(alphabet.length)] + generateName(length - 1);
}
return "";
}
I am creating a program that handles a car dealership. The user has the opportunity to add a car in the store by creating a random 3 digit number.
Now the question is how I can search/delete cars depending on the 3 digit code?
I'm thinking that I need every code that the cars have to save it on an array so I can search and delete afterwards.
I have created a class and certain methods on it, I have also created 5 objects and I'm trying to see if it works on these 5.
Here is the method of the random number:
I use the metritis variable because I can't achieve to place correctly the values on the array so I have to give parameter of 1,2,3,4,5 so I can place them correctly to the array.
package antiprosopeia;
import java.util.Random;
public class Antiprosopeia {
private String company,colour;
private int model,horsePower,speed,price,specialCode,metritis;
private int[] codes = new int[]{0,0,0,0,0};
public Antiprosopeia(String company, String colour, int model, int horsePower, int speed, int price) {
this.company = company;
this.colour = colour;
this.model = model;
this.horsePower = horsePower;
this.speed = speed;
this.price = price;
}
public Antiprosopeia() {
company = ""; colour = ""; model = 0; horsePower = 0; speed = 0; price = 0;
}
public void setRandomNumber(int metritis) {
Random rand = new Random();
int randNum2 = rand.nextInt(900) + 100;
specialCode = randNum2;
codes[metritis] = specialCode;
}
public void printarray() {
for(int i=0; i<codes.length; i++) {
System.out.println(" " + codes[i]);}
}
public void Info() {
System.out.println("Company : " + company + "\nColour : " + colour + "\nModel : " + model + "\nHorse Power : " + horsePower +
"\nSpeed : " + speed + "\nPrice : " + price );
}
public static void main(String[] args) {
Antiprosopeia car1 = new Antiprosopeia("Toyota","red",333,100,2223,8000);
car1.setRandomNumber(0);
Antiprosopeia car2 = new Antiprosopeia("Mercedes","yellow",233,100,2990,9000);
car2.setRandomNumber(1);
Antiprosopeia car3 = new Antiprosopeia("Volkswagen","green",153,100,2780,6000);
car3.setRandomNumber(2);
Antiprosopeia car4 = new Antiprosopeia("Mitsubisi","white",678,140,2600,7000);
car4.setRandomNumber(3);
Antiprosopeia car5 = new Antiprosopeia("Porsche","black",390,1000,2000,30000);
car5.setRandomNumber(4);
}
}
[EDIT] Now when i call the printarray() method it seems that at my array only one value is hold and all the others are zer0s as i defined the array at start of my program
If I were doing this, I would use a HashMap. This way you know that you have a unique 3 digit number, and if you wanted to, you could also store more data. You could do something like:
HashMap<Integer, Car> cars = new HashMap<Integer, Car>();
This example would allow you to add a car object to the map. You don't have to that, but it's an option. If you didn't want to do that, you could do:
HashMap<Integer, String> cars = new HashMap<Integer, String>();
and then do:
cars.put(123, "Description of car");
Using a HashMap would give you more options when storing the data. This would also prevent you from creating an array with 1000 elements, all of which are 0 until you have a value for them. You could easily print out all your numbers by doing:
for(int number : cars.entrySet()){
System.out.println("My car number: " + number);
}
Searching for keys would extremely easy, as you could do:
String description = cars.getKey(123);
If description was null, you would know that there is no key for it.
Your issue is that each Antiprosopeia object has its own codes array. They are not shared.
If you really want each object to have a Random ID, then assign that within the constructor.
public class Antiprosopeia {
private String company,colour;
private int model,horsePower,speed,price,specialCode,metritis;
private int randID;
public Antiprosopeia(String company, String colour, int model, int horsePower, int speed, int price){
this.company = company;
this.colour = colour;
this.model = model;
this.horsePower = horsePower;
this.speed = speed;
this.price = price;
this.randID = new Random().nextInt(900) + 100;
}
public Antiprosopeia(){
this("", "", 0, 0, 0, 0);
}
public int getID() { return this.randID; }
#Override
public String toString() {
return String.format(
"Company : %s\n" +
"Colour : %s\n" +
"Model : %s\n" +
"Horse Power : %d\n" +
"Speed : %d\n" +
"Price : %d\n",
company, colour, model, horsePower, speed, price
);
}
If you want to print all those objects,
public static void main(String[] args) {
List<Antiprosopeia> cars = new ArrayList<Antiprosopeia>();
cars.add(new Antiprosopeia("Toyota","red",333,100,2223,8000));
cars.add(new Antiprosopeia("Mercedes","yellow",233,100,2990,9000));
for (int i = 0; i < cars.size(); i++) {
Antiprosopeia c = cars.get(i);
System.out.println(c.getID());
System.out.println(c);
}
}
I am studying Java and have been asked to produce methods that can be used in order to gather statistics based off of the student names and marks that are entered. I have worked out how to calculate the top mark but what I need to do is return the name of the student that got the highest mark, how would I do this? I was thinking I could try to return the string before the highest int but I wasn't sure how I would do that.
Edit: Just to make it clear, currently, when END is entered in to the console following the input of data, the top mark is returned - I need to return the mark of the best student.
import java.util.*;
public class Course {
private ArrayList<Student> people = new ArrayList<Student>();
private int passing = 0;
private int failing = 0;
private int top = Integer.MIN_VALUE;
private int sum = 0;
public void add( Student student ) {
people.add( student );
if(student.getMark() >= 40){
passing++;
}
else {
failing++;
}
sum += student.getMark();
if(student.getMark() > top) {
top = student.getMark();
}
}
public int pass() {
return passing;
}
public int fail() {
return failing;
}
public int top() {
return top;
}
public double average() {
return sum / people.size();
}
}
Thanks for any help.
Update: BinaryJudy, I did what you said but I get a 'NoSuchMethod' error for the top name, this is what I changed my code to:
import java.util.*;
public class Course {
private ArrayList<Student> people = new ArrayList<Student>();
private int passing = 0;
private int failing = 0;
private int top = Integer.MIN_VALUE;
private int sum = 0;
private String topName;
public void add( Student student ) {
people.add( student );
if(student.getMark() >= 40){
passing++;
}
else {
failing++;
}
sum += student.getMark();
if(student.getMark() > top) {
top = student.getMark();
}
if(student.getMark() > top) {
top = student.getMark();
topName = student.getName();
}
}
public int pass() {
return passing;
}
public int fail() {
return failing;
}
public String top() {
return topName;
}
public double average() {
return sum / people.size();
}
}
Any idea why? :)
You have already found the student with the top mark. Update the top name with the name of the student when the top mark is found. Finding the top mark results in also finding the name.
String topName;
if(student.getMark() > top) {
top = student.getMark();
topName = student.getName();
}
Note that you're storing a bunch of students who I assume each have a mark for the course. All you need to do is cycle through that Arraylist, and find out who has the highest mark, and return that student.
Something like this may work for you:
public String topStu(ArrayList<Student> list) { // take in any list of students
int topStudentScore = 0; // default value
Student topStudent = null;
for (student x : list) { // cycle through all students in the list
if (x.getMark() > topStudentScore) { // if the score is higher than the current listed score
topStudentScore = x.getMark(); // update the top score
topStudent = x; // update top student
}
}
return topStudent.getName(); // return his name
}
You can easily write this to be a function for a specific course - you can remove the parameter, and directly access the private ArrayList if you want to.
Alternatively, you can write the above function to be a static function that takes any list of students from any course.
If a student is unique in the people list and insert order has no importance, then you can change
ArrayList<Student> people = ...;
By
// Java7 and before
SortedSet<Student> people = new TreeSet<>(new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s2.getMark()-s1.getMark(); // sorted by decreasing mark
}
});
// Java8
SortedSet<Student> people
= new TreeSet<>(Comparator.comparingInt(Student::getMark).reversed());
Then finding the top student is matter of getting the first from the people set:
Student top = people.first();
As a bonus, you can compute easily the ranking for all student. Adding new student will put them at the right ranking.
Note: Be aware that modifying a student mark after insertion will not change automatically its ranking and should be handled through a sequence of :
Student s = ...;
people.remove(s);
s.setMark(42);
people.add(s);
public class Classroom
{
Student[] students;
int numStudentsAdded;
public Classroom(int numStudents)
{
students = new Student[numStudents];
numStudentsAdded = 0;
}
public Student getTopStudent()
{
int y = 0;
//have to use numStudentsAdded
for ( int i = 0 ; i < numStudentsAdded ; i++)
{
if (students[y].getAverageScore() < students[i].getAverageScore())
{
y = i;
}
}
return students[y] ;
}
public void addStudent(Student s)
{
students[numStudentsAdded] = s;
numStudentsAdded++;
}
public void printStudents()
{
for(int i = 0; i < numStudentsAdded; i++)
{
System.out.println(students[i]);
}
}
}
Can anyone tell me where im going wrong I have three files Person.java Queue.java & Cinema.java, ive managed to do queues without objects Person.java but. I am having trouble implementing with objects.
Heres my Queue.java
public class Queue
{
private Person[] person = new Person[10];
private int rear;
public Queue()
{
rear = 0;
}
public boolean isEmpty()
{
return rear == 0;
}
public String remove() //remove String element
{
String result = person[0].toString(); //shuffle String elements
rear--;
for (int i = 0; i < rear ; i++)
{
person[i] = person[i + 1];
}
return result;
}
public void add(Person x) //add String element
{
if (rear == person.length)
{
resize();
}
person[rear] = x;
rear++;
}
private void resize()
{
Person[] temp = new Person[person.length * 2]; //resize String array
for (int i = 0; i < person.length; i++)
{
temp[i] = person[i];
}
person = temp;
}
}
Then heres Person.java (Object).
public class Person
{
private String name;
private int age = 0;
public Person(String name1, int age1)
{
this.name = name1;
this.age = age1;
}
}
And heres the main java file Cinema.java
import java.util.*;
public class Cinema {
public static void main (String[] args)
{
Queue q = new Queue();
Scanner k = new Scanner(System.in);
System.out.print("Enter name: ");
String name = k.nextLine();
System.out.print("Enter Age : ");
int age = k.nextInt();
q.add(name);
System.out.println(name + " joined queue");
}
}
Basically I want a person to join the queue with a name and age and the first person goes to buy the ticket and the age is checked. I can do the check bit its just getting it to read with objects.
Thanks
So I see two issues up here :
The Queue class seems to be implemented as a Stack rather than a Queue. I would suggest, Google about what queues are .
In your main method
String name = k.nextLine();
System.out.print("Enter Age : ");
int age = k.nextInt();
q.add(name);
Here, add method requires a person object as its parameter rather than a String object.
The code should be like :
String name = k.nextLine();
System.out.print("Enter Age : ");
int age = k.nextInt();
Person p1 = new Person(name,age);
q.add(p1);
Hope this helps.
EDIT!!!:
For your question in the comment. If you want to return age of the people in the Queue. You first would have to make two getter methods. One inside the Person class & other in the Queue class:
In person class:
public int getAge()
{
return age;
}
In Queue class:
public Person[] getPerson()
{
return person;
}
After writing these functions down. You can have the ages of people in the queue as :
Person[] p = q.getPerson(); // q is the Queue object
for(int i=0;i<p.length;i++)
{
if(p[i]!=0)
{
System.out.println(p[i].getAge());
}
}
Hope this helps. if this helps you reach the solution of your problem, do upvote and select the answer as correct one.