What is wrong with this Company Class OOP program? - java

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.

Related

Reading from keyboard to build a relationship between objects

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);
....

Values not printed out when using Comparator to sort ArrayList

I'm working on a program where I'm inputting values(String and int) into arrays, putting those values into an objects which go into an array list to be sorted by the the int value. When I run the program though, it prints out:
Sorted List Entries:
Item Name:null---Quant:0
Item Name:null---Quant:0
Item Name:null---Quant:0 //etc..
I'm trying to learn on my own here but I'm not sure what to do.
My main class:
import java.io.*;
import java.util.*;
public class InputItem
{
public static void main(String args[])
{
String again;
String names[] = new String[100];
int quant[] = new int[100];
int row=0;
do{
System.out.println("Please input assignment name:");
Scanner newName = new Scanner(System.in);
String name = newNamet.next();
names[row] =name;
System.out.println("Please input assignment quant:");
Scanner quantI = new Scanner(System.in);
int quantity = quantI.nextInt();
quant[row] = quantity;
System.out.println("Would you like to add another item? Enter 'Yes' or 'No'");
Scanner input = new Scanner(System.in);
again = input.next();
row++;
}
while(again.equalsIgnoreCase("Yes"));
List<Items> work = new ArrayList<Items>();
for(int count = 0; count<row; count++)
{
work.add(new Items((names[row]),(quant[row])));
}
Collections.sort(work, new MyComp());
System.out.println("Sorted List Entries: ");
for(Items e:work)
{
System.out.println(e);
}
}
}
Class with Comparator:
import java.util.*;
class MyComp implements Comparator<Items>
{
#Override
public int compare(Items e1, Items e2)
{
if((e1).getQuant()< (e2).getQuant())
{
return 1;
}
else
{
return -1;
}
}
}
public class Items
{
private String name;
private int quant;
public Items(String n, int q)
{
this.name = n;
this.quant = q;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getQuant()
{
return quant;
}
public void setQuant(int quant)
{
this.quant = quant;
}
public String toString()
{
return "Item Name:" + this.name+"---Quant:" +this.quant;
}
}
The problem is here...
for (int count = 0; count < row; count++) {
work.add(new Items((names[row]), (quant[row])));
}
You're using row, which was defined in the previous section of code to keep track of which element you were updating, but is now pointing to the next element in the array (or an empty element). This basically means you are constantly adding the same (empty) values to your Items
Instead, you should be using count
for (int count = 0; count < row; count++) {
work.add(new Items((names[count]), (quant[count])));
}

Iterate through ArrayList

I'm currently trying to iterate through an ArrayList and see if it contains the following numbers I input into the winners array. However, the ticket object won't allow me to utilize the .contains() method which is where I'm getting the error. Any idea on how to work around this?
int[] winners = new int[6];
for(int i = 0; i < winners.length; i++)
{
winners[i] = in.nextInt();
}
in.close();
Scanner scan = new Scanner(file);
ArrayList<Ticket> info = new ArrayList<Ticket>();
for(int i = 0; i < lim; i++)
{
String name = scan.nextLine();
String num = scan.nextLine();
String[] t = num.split(" ");
int[] tichold = new int[t.length];
for(int j = 0; j < t.length; j++)
{
tichold[j] = Integer.parseInt(t[j]);
}
Ticket ticket = new Ticket(name, tichold);
info.add(ticket);
}
**for(Ticket t : info)
{
if(t.contains(winners))
{
System.out.println("Yes");
}
}**
scan.close();
}
**public static class Ticket
{
public String name;
public int[] tarray;
public Ticket(String name, int[] tarray)
{
this.name = name;
this.tarray = tarray;
}**
You can't use a method that doesn't exist for that class. Since you don't have contains defined for Ticket, I'm not surprised that it isn't working.
From inference, winners is an int[]. In that case, you'd define a new method contains inside of Ticket.
public boolean contains(int[] winningNumbers) {
// logic here
}
Depending on how the winning numbers for a given ticket are stored, and given how you define different conditions of winning, you'd handle your logic here.
If they're stored as an array and you want an exact match, then you can use Arrays.equals for that.
public boolean contains(int[] winningNumbers) {
return Arrays.equals(numbers, winningNumbers);
}
Try this Ticket class with and added contains method:
public class Ticket {
public String name;
public int[] tarray;
public Ticket(String name, int[] tarray)
{
this.name = name;
this.tarray = tarray;
}
public boolean contains(int[] winners) {
for (int i = 0; i < winners.length; i++) {
for (int j = 0; j < tarray.length; j++) {
if (winners[i] == tarray[j])
return true;
}
}
return false;
}
}

How do I find the name of the top student in an array list?

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]);
}
}
}

Ready to pull my hair out Java Queues with objects

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.

Categories

Resources