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.
Related
i hope someone can help me, i'm struggling with this since yesterday...
I'm working right now on a Hotel Management System project.
What i'm trying to do is, to put an array[] Clients into an ArrayList of Rooms and then set this room attribute to 'occupied = true' and save that so if i try to use that room for other client it doesn't let me.
Room class
public class Room {
private int number;
private float price= 30.5f;
private boolean occupied = false;
private Client[] hosts;
public Room(int number, Client[] hosts) {
this.number= number;
this.hosts= hosts;
}
public void setOccupied() {
this.occupied = true;
}
}
Client class
public class Client {
private String id;
private String name;
private String lastName;
public Client(String id, String name, String lastName) {
this.id = id;
this.name= name;
this.lastName= lastName;
}
}
This is what i've got on my Main so far... i'm calling the next function
public void checkIn(ArrayList<Room> myRooms){
int roomNumber;
String id;
String name;
String lastName;
Scanner input = new Scanner(System.in);
int people = input.nextInt();
Client[] array = new Client[people];
for (int i = 0; i < people; i++) {
System.out.println("Enter ID" + (i+1));
id = input.next();
System.out.println("Enter name " + (i+1));
name= input.next();
System.out.println("Enter last name " + (i+1));
lastName= input.next();
array[i] = new Client(id,name,lastName);
}
System.out.print("Assign to room number... : ");
roomNumber = input.nextInt();
myRooms.add(new Room(roomNumber, array));
//here i tried doing:
//room.set().setOccupied();
//room.set(roomNumber).setOccupied();
//but .set() expects an index...
}
Once i have this, i want to create a function that shows a list of rooms that are occupied
Excuse my english since i'm Spanish
Several ways to tackle this, probably what i would do is overload my room constructor so that you can set if it's occupied or not once you instantiate it like:
public Room(int number, Client[] hosts, boolean occupied)
{
this.number = number;
this.hosts = hosts;
this.occupied = true;
}
and in your checkIn() method just add true when instantiating your room inside the list:
myRooms.add(new Room(roomNumber, array, true));
Since you aren't creating a reference-able instance of Room when you call
myRooms.add(new Room(roomNumber, array));
you can't then say
room.setOccupied();
You can fix this two ways: First, as Bahij.Mik said, you could call this.occupied = true; in the Room constructor. Or, you could simply create a new instance of a Room in your checkIn method. This would look like:
Room newRoom = new Room(roomNumber, array);
newRoom.setOccupied();
whenever someone checks in.
As for creating a function to check which rooms are occupied, make an array of room numbers and then try:
public String[][] findOccupiedRooms(int[] roomNumbers) {
String[][] roomList = new String[roomNumbers.length][1];
for(int i = 0; i < roomNumbers.length; i++) {
if(roomNumbers[i].isOccupied() == true) {
roomList[i][0] = "" + roomNumbers[i];
roomList[i][1] = "occupied";
} else {
roomList[i][0] = "" + roomNumbers[i];
roomList[i][1] = "vacant";
}
}
return roomList[][];
}
This returns a 2-dimensional array that stores the room number and whether it is occupied or vacant. Not sure if this is exactly what you are looking for, but I hope it helps.
I want to create an object named "Course", and get the information from the keyboard. The last attribute called the "pre", which means the prerequisite courses of this course. I want to input the whole information in one line and extract the information for each attribute. But I got the problem with"pre". I run the program and the output of course.pre is null. I do not know why. Here is my Course class code:
`import java.util.HashSet;
public class Course{
private String name;
private int isFall;
private int NumPre;
private HashSet<Course> pre;
public Course(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String setName (String n){
return name = n;
}
// 1 - fall 0 - both -1 - spring
public void setType(String isFall) {
if(isFall.equals("F") || isFall.equals("f")){
this.isFall = 1;
}else if(isFall.equals("S") || isFall.equals("s")){
this.isFall = -1;
}else if(isFall.equals("B") || isFall.equals("b")){
this.isFall = 0;
}
}
public int getType(){
return isFall;
}
public void SetNumPre(int n) {
this.NumPre = n;
}
public int getNumPre() {
return NumPre;
}
public void addPre(Course c) {
pre.add(c);
}
public HashSet<Course> getPre() {
return pre;
}
}
`
And here is my main method here:
import java.util.*;
public class TimeToGraduate {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
//System.out.print("Input first two integers here: ");
String globalInfo = scanner.nextLine();
String[] numOfCourse = globalInfo.split(" ");//[0] num of total course [1] max num per semester
int totalNum = Integer.parseInt(numOfCourse[0]);
int maxPre = Integer.parseInt(numOfCourse[1]);
Course courses[] = new Course[totalNum];
//System.out.print("Please input course list here: ");
String coursesList = scanner.nextLine();
String[] nameOfCourse = coursesList.split(" ");
for(int i = 0;i < totalNum; i++){
courses[i] = new Course(nameOfCourse[i]);
}
//System.out.print("Please input course info here: ");
for(int i = 0;i < totalNum; i++){
String courseInfo = scanner.nextLine();
String[] infoOfCourse = courseInfo.split(" ");
courses[i].setName(infoOfCourse[0]);
courses[i].setType(infoOfCourse[1]);
courses[i].SetNumPre(Integer.parseInt(infoOfCourse[2]));
if(courses[i].getNumPre() > 0){
for(int j = 3; j < 3+(courses[i].getNumPre()); j++){
for(int k = 0; k < totalNum; k++){
if(infoOfCourse[j] == courses[k].getName()){
courses[i].addPre(courses[k]);
}
}
}
}
}
scanner.close();
for(int m = 0; m < totalNum; m++){
System.out.print(courses[m].getName()+" ");
System.out.print(courses[m].getType()+" ");
System.out.print(courses[m].getNumPre()+" ");
System.out.print(courses[m].getPre()+" ");
System.out.println();
}
}
}
Notice that you did not initilize the pre attribute. That is why it is null.
It would be a good practise if you initilize the pre inside a constructor for the Course class. Otherwise, do it when you start filling the Course attributes.
Update:
Your constructor should be like this:
public Course() { this.pre = new HashSet()}
As you can see the constructor does not have any arguements, because you will be filling its attribute from the main function.
You can define a constructor with arguments too:
public Course(String name, HashSet<Course> pre)
{ this.name = name; this.pre = pre; }
But you will need to initilize pre and name when you call it from the main:
...
HashSet hs = new HashSet();
course[i] = new Course('course_name', hs);
....
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]);
}
}
}
Having trouble figuring out exactly how to do this. Ive wrote 10 different things and worked on it for 8 hours and have yet to figure out how to get this to work. What I'm trying to do with this program is get a the persons name, friends name, persons age, friends age, and persons popularity (All of this from a .txt file with each line as : Michelle, 12/20/2008, Camilla) . I have gotten the persons name to output correctly, persons age to output correctly, and persons friend to output correctly. But having trouble with popularity and getting friends age from personsofinterest's age.
What I need help with :
1.Popularity points adding up and returned for each time the personOfInterest is in the name array. With the popularity I have went back and debugged it after i was getting 0 for every popularity for each person. And I got that it wasn't adding anything to the return, I tried many different ways but still could not figure it out.
2.Setting personOfInterest name to certain age to be used as friendsAge if the users friend is a personOfInterest already found age for.(All personOfInterest names in .txt field is someones friend)
friends_data.txt :
Michelle, 12/20/2008, Camilla
Bryan, 3/8/2007, Tom
Camilla, 6/7/2005, Michelle
Tom, 10/15/2007, Bryan
Charlotte, 3/2/2008, Michelle
I believe my code looks a little messy, started going back and throwing things together I thought would work.
Person Class :
import java.util.ArrayList;
public class Person {
public String personsName;
public String personsFriend;
public String personsBirthday;
public int personsPopularity;
public int popularity = 0;
public ArrayList<String> friends = new ArrayList<>();
public Person(String aName, String aFriend, String aBirthday) {
personsName = aName;
personsFriend = aFriend;
friends.add(personsFriend);
personsBirthday = aBirthday;
}
public String getName() {
return personsName;
}
public String getFriendsName() {
return personsFriend;
}
public String getBirthday() {
return personsBirthday;
}
public void getPopularityNumber(){
for(int i = 0; i < friends.size(); i++){
if (personsName.equals(friends.get(i))){
popularity = 1 + popularity;
}
else
popularity = popularity;
}
System.out.println(popularity);
}
public String getFriend() {
return personsFriend;
}
public int getAge() {
int MONTH = 0;
int DAY = 0;
int YEAR = 0;
for (int i = 0; i < 3; i++) {
String[] dates = personsBirthday.split("/");
String month = dates[0];
String day = dates[1];
String year = dates[2];
MONTH = Integer.parseInt(month);
DAY = Integer.parseInt(day);
YEAR = Integer.parseInt(year);
}
int age = (2014 - YEAR);
int moAge = (5 - MONTH);
if (moAge < 0) {
age--;
}
return age;
}
}
Main File :
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class PersonTester {
public static void main(String[] args) throws FileNotFoundException {
//Get that file and start the scan on that broseph
File inputFile = new File("friends_data.txt");
Scanner in = new Scanner(inputFile);
//Set up an array for our Person objects
final int SIZE = 5;
Person[] personsOfInterest = new Person[SIZE];
String[] friends = new String[5];
//Lets get this i declared as 0 for our array!
int i = 0;
int popularity = 0;
String person;
while (in.hasNextLine()) {
String line = in.nextLine();
String[] nameBirthdayname = line.split(", ");
person = nameBirthdayname[0];
String birthday = nameBirthdayname[1];
String friend = nameBirthdayname[2];
friends[i] = friend;
personsOfInterest[i] = new Person(person, friend, birthday);
i++;
}
for (i = 0; i < SIZE; i++) {
System.out.println("");
System.out.println("New Person");
System.out.println("--------------------------------------------------------");
System.out.println("Persons Name : " + personsOfInterest[i].getName());
System.out.println("Popularity : " + personsOfInterest[i].getPopularityNumber());
System.out.println("Their age on May 1, 2014 : " + personsOfInterest[i].getAge());
System.out.println("Persons Best Friend : " + personsOfInterest[i].getFriend());
System.out.println("Best Friends Age on May 1,2014 : " + personsOfInterest[i].getName());
System.out.println("--------------------------------------------------------");
}
}
}
Have Also Tried this for getPopularityNumber Method :
public void getPopularityNumber(String[] friends) {
for (int i = 0; i < 5; i++) {
if (personsName.equals(friends[i])) {
popularity = 1 + popularity;
} else
popularity = popularity;
}
System.out.println(popularity);
}
Any help would be greatly appreciated!
The point is to write a program that finds an employee by searching by their id number, and by printing out all the information of all the employees and by printing out the information of a single employee. I need help with that (the search) and if printing a single employee alone is correct? Thanks!
Class Employee code:
public class Employee {
private String name;
private int id;
private int salary;
private boolean bonus;
public Employee(String n, int i, int s, boolean b) {
name = n;
id = i;
salary = s;
bonus = b;
}
public void computeSalary(int s, boolean b) {
if (b == true)
salary += 2000;
}
public void printInfo() {
System.out.print("Name: "+name+" ID: "+id+" Salary: "+salary+" Bonus: "+bonus+" ");
}
Class EmployeeApp class code:
import java.util.Scanner;
public class EmployeeApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the name: ");
String n = in.nextLine();
System.out.print("Enter the ID: ");
int g = in.nextInt();
System.out.print("Enter the salary: ");
int s = in.nextInt(); in.nextLine();
System.out.print("true or false for bonus? ");
boolean b = in.nextBoolean();
Employee e = new Employee(n, g, s, b);
e.computeSalary(s, b);
e.printInfo();
}
}
public class Company{
private Employee[] e = new Employee[4];
public void printAllEmployees() {
for(int i = 0; i < e.length; i++)
e[i].printInfo();
}
public Employee searchEmployee(int i) {
Employee temp = null;
for (int j = 0; j < e.length; j++) {
if (Employee.id == i)
temp = Employee;
}
return temp;
}
public void printAnEmployee(Employee e) {
e.printInfo();
}
}
put employees in a structure that will enable simple searching latter, like the following:
private Map<Integer, Employee> e = new HashMap<Integer, Employee>();
public void printAllEmployees() {
for( Integer key : e.keySet() )
System.out.println(e.get( key ));
}
public Employee searchEmployee(int i) {
return e.get(i);
}
I do not know how the code that you gave us works for even for an user because you have a minor issues in your classes.
First, it is a good practice to have setter and getter in your Employee because for safety is good to encapsulate a object , so how to construct them plz refer to this tutorial
http://www.tutorialspoint.com/java/java_encapsulation.htm
Second, in your EmployeeApp class
when you ask this
System.out.print("true or false for bonus? ");
boolean b = in.nextBoolean();
is not clear what kind of input user has to enter, so it is good to change first line to
System.out.print("true or false for bonus? \nplease enter true or false");
Third, it is good to put your company class in different file, and some minor issue in your Company class as follow
Note: Employee is a class and e is an array with Employee type
public Employee searchEmployee(int i) {
Employee temp = null;
for (int j = 0; j < e.length; j++) {
if (**Employee.id** == i)
**temp = Employee;**
}
return temp;
}
change to
public Employee searchEmployee(int i) {
Employee temp = null;
for (int j = 0; j < e.length; j++) {
if (e[i].getId() == i) {
temp = e[i];
}
}
return temp;
}
At the end, if you need to add more employee, you need to put it in a while loop. Hence, while loop is going to be ok till for example an user push X.