Im just start learning java renow .i created a class student which contain variable ID and name and another class studentlist that is an arraylist of student.
I want to create seach function that allow to pass variale's name of stunt class (ID or name) and the variable value. how can i do it ?
class Student{
String ID;
String name;
public Student(){
}
public Student(String ID,String name){
this.ID = ID;
this.name = name;
}
public String getStudent() {
String info = this.ID +"\t\t\t"+ this.name;
return info;
}
}
class StudentList{
private ArrayList <Student> list = new ArrayList<>();
private int counter = 0;
static Scanner sc = new Scanner(System.in);
public StudentList(){
}
public StudentList(Student stu){
Student student = new Student(stu.ID,stu.name);
this.list.add(student);
this.counter++;
}
public int seach(String type(name or ID) , String value ){
int i;
int found = 0;
for(i = 0; i < list.size();i++){
if(value.equals(list.get(i).type){
found++;
System.out.println(value.equals(list.get(i).type);
}
}
return found;
}
}
Create getter for ID and name in Class Student.
Than you can ask in seach
public int seach(String type , String value ){
int i;
int found = 0;
for(i = 0; i < list.size();i++){
Student student = list.get(i);
if(value.equals(student.getID()) || value.equals(student.getName())){
found++;
System.out.println(value.equals(list.get(i).type);
}
}
return found;
}
First I recommend to set the attributes of your Student class to private. Then you could add setters and getters.
public class Student {
private String ID;
private String name;
public Student() {}
public Student(String ID, String name) {
this.ID = ID;
this.name = name;
}
public String getID() { return ID; }
public String getName() { return name;
public void setID(String ID) { this.ID = ID; }
public void setName(String name) { this.name = name; }
}
In your class StudentList I would split and extend the functionalities of the search instead of passing the value type as an additional argument.
public class StudentList {
...
public int searchByName(String name) {
for(int i=0; i < list.size(); i++) {
if(list.get(i).getName().equals(name)) return i;
}
return -1;
}
public int searchByID(String ID) {
for(int i=0; i < list.size(); i++) {
if(list.get(i).getID().equals(ID)) return i;
}
return -1;
}
public int searchStudent(Student stud) { return list.indexOf(stud); }
}
If you really need a function that bundles all of that you could add another function that decides by a flag which function should be called with the passed argument. You could also add a check for arguments here while having more flexibility and separation of responsibilities.
public int search(int flag, arg Object) {
if(flag == 0) return searchStudent((Student) arg);
else if(flag == 1) return searchByID((String) arg);
else return searchByName((String) arg);
}
Additional side note: if you want to indicate the current number of students in the list with your counter variable, I highly recommend to remove this variable and always call the size() method of your list when needed. Every Java collection (i.e. ArrayList) provides it and it will always return the correct value after removing or adding students. Implementing your own counter for this task will result in a more error prone source code.
Related
I couldn't find a solution anywhere, so here it is:
A school project says that to use isEqual(Student) method I must use the hasSameName(Person) inside it.
I have created two classes, Student and Person where boolean hasSameName(Person persons[]) compare the names inside the array and returns true if same name found and false if there's no same person.
public class Person{
private String name,surname,address,email,phoneNumber;
public Person(String name,String surname,String address,String email,String phoneNumber) {
this.name = name;
this.surname = surname;
this.address = address;
this.email = email;
this.phoneNumber = phoneNumber;
}
...
...
...
public boolean hasSameName(Person persons[]) {
boolean flag = false;
for(int i = 0; i<persons.length; i++) {
for (int j = i+1; j< persons.length; j++) {
if((persons[i].getName() == persons[j].getName() && (i!=j))){
flag = true;
}
}
}
if(flag == true)
return true;
else
return false;
}
The project says that boolean isEqual(Student name, Student id) should compare the name and the id values but hasSameName(Person) method must be used.
Here is the Student class:
public class Student extends Person {
private int studentID,semester;
public Student(String name,String surname,String address,String email,String phoneNumber,int studentID,int semester) {
super(name,surname,address,email,phoneNumber);
this.studentID = studentID;
this.semester = semester;
}
.
.
.
.
public boolean isEqual(Student name,Student id) {
//****************i am stuck here. I don't know how to make it work.*******************
}
Any help will be appreciated.
A school project says that to use isEqual(Student) method I must use the hasSameName(Person) inside it.
I assume that hasSameName method should have been implemented like this:
// Person.java
public boolean hasSameName(Person person) {
if (null == person || null == person.getName())
return false;
return person.getName().equals(this.getName());
}
Then, as Student extends Person, you can simply call parent's methods from the child class. So, providing that the signatures of hasSameName and isEqual have been fixed, isEqual may be implemented this way:
// Student.java
public boolean isEqual(Student student) {
return this.hasSameName(student) && this.studentID == student.getStudentID();
}
I keep on getting an error saying Cannot find symbol when trying to compile. The files are both in the same folder, i'm not really sure where i went wrong here.
In this assignment im supposed to write a program that reads a list of employees from a file. The name of the file will be ‘Employee.txt’. The program should output the sorted array to a file called “SortedEmployee.txt”. I already have the Heap class done. Need assistance please.
public class Employee
{
String id;
String name;
String department;
String position;
double salary;
int yos; //Year of Service
//constructor w/ no args
public Employee()
{ salary = 0.0;
id = name = department = position = "";
yos = 0;
}
//constructor w/ args
public Employee(String i, String n, String d, String p, double s, int y)
{
id = i;
name = n;
department = d;
position = p;
salary = s;
yos = y;
}
public void setID(String i)
{ id = i;}
public void setName(String n)
{ name = n;}
public void setDepartment(String d)
{department = d;}
public void setPosition(String p)
{position = p;}
public void setSalary(double s)
{salary =s;}
public void setYOS(int y)
{yos = y;}
public String getID()
{ return id;}
public String getName()
{ return name;}
public String getDepartment()
{return department;}
public String getPosition()
{return position;}
public double getSalary()
{return salary;}
public int getYOS()
{return yos;}
public String toString()
{
String str = "Emplyee Id: " + id + "\nName: " + name +
"\nDepartment: " + department + "\nPosition: " + position
+ "\nSalary: " + salary;
return str;
}
public int compareTo(Employee emp)
{
int idONE = id.compareToIgnoreCase(emp.id);
if (idONE != 0)
return idONE;
return 0;
}
}
public class EmployeeCOMP implements Comparable<Employee>{
#Override
public int compareTo(Employee emp){
return this.id.compareToIgnoreCase(emp.id);
}
}
This is the error I keep on getting.
EmployeeCOMP.java:4: error: cannot find symbol
return this.id.compareToIgnoreCase(emp.id);
^
symbol: variable id
1 error
this refers to the instance of EmployeeCOMP which does not have an id. In this context the compareTo method should be part of the Employee class (not a separate class):
public class Employee {
...
public int compareTo(Employee emp) {
return this.id.compareToIgnoreCase(emp.id); // **this** refers to an Employee instance
}
}
Attempting to use through a separate class suggests you might be needing to implement a Comparator.
I take in a file which has a name (table) and the number of seats:
table1 6
table2 2
table3 4
I have an array of class Reservation which will take in the the name and the seat. I am having trouble converting the number of seats into the array. How do i go about doing so?
public class Reservable {
protected String id;
private Reservation[] arrayRes = new Reservation[10];
public Reservable (Scanner fileIn) {
while(fileIn.hasNext()) {
id = fileIn.next();
for(int i = 0; i < arrayRes.length; i++) {
int seat = fileIn.nextInt();
arrayRes[i] = seat;
}
}
}
here is my Reservation class:
public class Reservation {
private String name;
private int timeSlot;
private Reservable myReservable;
public Reservation(String name, int timeSlot) {
this.name = name;
this.timeSlot = timeSlot;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTimeSlot() {
return timeSlot;
}
public void setTimeSlot(int timeSlot) {
this.timeSlot = timeSlot;
}
public Reservable getMyReservable() {
return myReservable;
}
public void setMyReservable(Reservable myReservable) {
this.myReservable = myReservable;
}
public boolean isActive() {
return false;
}
You can read line by line since your file has a reservation by line.
I propose you to have a Reservation constructor with two parameters (name and nbSeat).
A remark : you array of reservation has a fixed size : 10. If you file has more than 10 elements, a ArrayIndexOutOfBoundsException will be risen.
If the number of reservation may be superior to 10 or is variable, you should use a List rather than a array.
protected String id;
private Reservation[] arrayRes = new Reservation[10];
public Reservable (Scanner fileIn) {
int i=0;
while(fileIn.hasNextLine()) {
String line = fileIn.nextLine();
String[] token = line.split("\\s");
String name = token[0];
int nbSeat= Integer.valueOf(token[1)];
// add in your array
Reservation reservation = new Reservation(name,nbSeat);
arrayRes[i] = reservation ;
}
i++;
}
And Reservation :
public class Reservation{
public Reservation(String name, int nbSeat){
this.name=name;
this.nbSeat=nbSeat;
}
}
You need to show us what your Reservation class looks like, but if it uses the conventional getters and setters this is the correct way:
public Reservable (Scanner fileIn) {
while(fileIn.hasNext()) {
for(int i = 0; i < arrayRes.length; i++) {
int seat = fileIn.nextInt();
arrayRes[i].setSeat(seat);
id = fileIn.next();
arrayRes[i].setId(id);
}
}
}
this is my current code to store rooms(it compiles fine) but in the UML there is a variable called addEquipment and there is also another class called Equipment to be defined. I'm having trouble wrapping my head around what I'm supposed to do with this. Am I supposed to create and call an object called Equipment? what goes in addEquipment?
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private String equipmentList;
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public String getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(String anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
}
//Create room object
public Room(int capacity, String equipmentList) {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
return "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
}
}
You can create a new class Equipment and modify your attribute equipmentList to be a List:
public class Equipment {
private String name;
public Equipment(String name) {
this.name = name;
}
}
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private List<Equipment> equipmentList = new ArrayList<Equipment>();
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public List<Equipment> getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(List<Equipment> anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
Equipment oneEquipment = new Equipment(newEquipment);
equipmentList.add(oneEquipment);
}
//Create room object
public Room() {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
String capacity=String.valueOf(getCapacity());
String room = "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
return room;
}
}
In the method addEquipment, you can create a new Equipment and add it to equipmentList, like code above.
An Equipment class could be anything. Lets assume the "Equipment"-class has a String called "name" as it's attribute
public class Equipment {
String name;
public Equipment( String name) {
this.name = name;
}
public String getName() {
return this.name
}
}
When you extend your Room class by the requested "addEquipment" method, you can do something like this.
public class Room {
... // Your code
private int equipmentIndex = 0;
private Equipment[] equipment = new Equipment[10]; // hold 10 Equipment objects
public void addEquipment( Equipment eq ) {
if ( equipmentIndex < 10 ) {
equipment[ equipmentIndex ] = eq;
equipmentIndex++;
System.out.println("Added new equipment: " + eq.getName());
} else {
System.out.println("The equipment " + eq.getName() + " was not added (array is full)");
}
}
}
Now when you call
room.addEquipment( new Equipment("Chair") );
on your previously initialized object of the Room-class, you will get
"Added new equipment: Chair"
Hope this helps a bit.
PS: The code is untestet (maybe there hides a syntax error somewhere)
What i wanna do is to remove an object from a table of object ONLY IF the object i wanna delete have the id i put in params.
Let's get into the code :
public static animals[] supprimerAnimals(int identifiant, animals[] liste){
animals[] newOne = new animals[0];
for(int i = 0; i < liste.length; i++){
}
return newOne;
}
This method will receive a id and a table in params.
In the table, we have objects... let's tell them animals. Here is a list of objects we could have :
liste[0] = animals(1, "cat", 6)
liste[1] = animals(2, "dog", 4)
here would be the constructor :
animals(int id, String type, int age);
So we have all we would need to get the solution.
So now let's get into an example...
If i do this :
animals[] zoo = supprimerAnimals(2, liste);
I need that zoo contains this :
zoo[0] = animals(1, "cat", 6);
Can you guys put me on the right way please ?
I'm getting lock on the fact that i have to create a new table and i don't even now if the id will exist on the old table... So i can't fix the size of the new table...
Thank you guys
animals[]
means that there is a java Object called animals, and the items in that array have this DataType "animals"
bellow i created an Object named Animal and here is an example with 2 ways of doing that
public class Animal{
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
now some where you can implement the deleteMethods something like:
public static Animal[] removeAnimal(Animal[] animals, int id) {
List<Animal> list = Arrays.asList(animals);
for(Animal item : animals)
if( item.getId() == id )
list.remove(item);
return list.toArray(animals);
}
OR
public static Animal[] removeAnimal2(Animal[] animals, int id) {
Animal[] arr = new Animal[animals.length-1];
int i = 0;
for(Animal item : animals){
if( item.getId() != id ){
try{
arr[i]=item;
}catch(Exception ex){
ex.printStackTrace();
}
}
}
return arr;
}
See if this suits your need.
public static animals[] supprimerAnimals(int identifiant, animals[] liste) {
int supprimer = -1;
for (int i = 0; i < liste.length; i++) {
if (liste[i].getId() == identifiant) {
supprimer = i;
break;
}
}
if (supprimer < 0) {
return liste;
}
animals[] nouveauListe = new animals[liste.length - 1];
for (int i = 0; i < supprimer; i++) {
nouveauListe[i] = liste[i];
}
for (int i = supprimer + 1; i < liste.length; i++) {
nouveauListe[i - 1] = liste[i];
}
return nouveauListe;
}
Note
Java class names by convention are PascalCase and are singular, not plural
Just Check out this. I have used list instead of Arrays.
package com.Hangman;
import java.util.ArrayList;
import java.util.List;
public class Test5 {
public static void main(String[] args) {
List zoo= new ArrayList();
Animal animal= new Animal(1,"cat",01);
zoo.add(animal);
animal= new Animal(6,"dog",02);
zoo.add(animal);
animal= new Animal(3,"mouse",03);
zoo.add(animal);
animal= new Animal(8,"rabbit",04);
zoo.add(animal);
animal= new Animal(5,"lion",05);
zoo.add(animal);
System.out.println("List of Animals in zoo");
System.out.println(zoo);
System.out.println("Animal to be removed from zoo is having id 3");
removeFromZoo(zoo, 3);
System.out.println("Animals in zoo after removal");
System.out.println(zoo);
}
static void removeFromZoo(List zoo,int id){
Animal animal= new Animal(id,null, 0);
zoo.remove(animal);
}
}
class Animal{
int id;
String type;
int age;
public Animal(int id, String type, int age) {
super();
this.id = id;
this.type = type;
this.age = age;
}
#Override
public String toString() {
return ""+this.type;
}
#Override
public boolean equals(Object animal) {
if(animal instanceof Animal){
return this.id==((Animal) animal).id;
}else
return false;
}
}