How to use boolean with constructor in java? - java

We have an activity that will store and display the information of an employee.
I've already created no-modifier class named Person and a public class named Employee which is the the main method. My problem is I don't know how to make the boolean in the class Person which will be used in the main method with a scanner.
class Person {
private String name;
private int contactNum;
private boolean status;
public boolean isRegular;
public String getName(){
return name;
}
public int getContactNum(){
return contactNum;
}
public void setName(String name){
this.name=name;
}
public void setContactNum(int contactNum){
this.contactNum=contactNum;
//how to make the boolean of status and isRegular?
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Person P = new Person();
System.out.println("Type employee's name, contact number");
System.out.println("Press Enter after every input");
P.setName(input.nextLine());
P.setContactNum(input.nextInt());
System.out.println("Press Y if employee is regular or N if not");
//how to use boolean here that comes from the class Person?
System.out.println("Name: "+ P.getName());
System.out.println("Contact Number: "+ P.getContactNum());
System.out.println("Status:" + this is where the user is ask to Press Y if employee is regular or N if not )//the status is if the employee is regular or not.

My suggestion for your code:
System.out.println("Press Y if employee is regular or any other key if not");
P.setRegular(input.nextLine().equalsIgnoreCase("Y"));
Your constructor
public class Person {
private String name;
private int contactNum;
private boolean status;
private boolean isRegular;
//No arg constructor
public Person() {
}
//Full arg constructor
public Person(String name, int contactNum, boolean status, boolean isRegular) {
this.name = name;
this.contactNum = contactNum;
this.status = status;
this.isRegular = isRegular;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getContactNum() {
return contactNum;
}
public void setContactNum(int contactNum) {
this.contactNum = contactNum;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public boolean isRegular() {
return isRegular;
}
public void setRegular(boolean regular) {
isRegular = regular;
}
}
Edit
I've noticed an error in the above code and fixed it. This line should be:
P.setRegular(input.next().equalsIgnoreCase("Y"));
You can print booleans as is just like any other Java primitive. `
System.out.println("Status:" + P.isRegular());
would print Status: true or Status: false.
If you want it to print Status: Yes or Status: No, you could do something like this:
System.out.println("Status: ".concat((P.isRegular())?("Yes"):("No")));

Related

Checking if an object is in arraylist in Java

So here is assignment :
A student entity has a name and an address (both represented by an object of class Name and Address), in addition to a university ID, and a course schedule represented by an ArrayList of Courses
Your code should not allow the creation of Two students with the same university ID
So I'm thinking of using ArrayList to hold a list of student and check if student exists or not before create a new student. sorry, this is my first question so I'm trying my best to explain it:
This is my Address class:
public class Address {
private int streetNumber;
private String streetName;
private String city;
private String state;
private int province;
private String country;
public Address (int streetNumber,String streetName,String city,String state,int province,String country)
{
this.streetNumber=streetNumber;
this.streetName=streetName;
this.city=city;
this.state=state;
this.province=province;
this.country=country;
}
public int getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(int streetNumber) {
this.streetNumber = streetNumber;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public int getProvince() {
return province;
}
public void setProvince(int province) {
this.province = province;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String toString() {
return " [streetNumber=" + streetNumber + ", streetName=" + streetName
+ ", city=" + city + ", state=" + state + ", province="+province+", country="
+ country + "]";
}
public boolean equals(Address add)
{
if(add==null)
{
return true;
}
if(this.getClass()!=add.getClass())
{
return false;
}
Address address=(Address) add;
return streetNumber==address.streetNumber &&
province==address.province && streetName.equals(address.streetName)
&& city.equals(address.city)&& state.equals(address.state)&& country.equals(address.country);
}
}
This is my Name class
public class Name {
private String firstName;
private String lastName;
private char middle;
public Name (String fiName,String laName, char middle)
{
this.firstName=fiName;
this.lastName=laName;
this.middle=middle;
}
public String getFirst()
{
return firstName;
}
public void setFirst(String first)
{
firstName=first;
}
public String getLast()
{
return lastName;
}
public void setLast(String last)
{
lastName=last;
}
public char getMiddle()
{
return middle;
}
public void setMiddle(char midd)
{
middle=midd;
}
/*public String toString()
{
return "[First Name= "+ firstName +" Last Name "+ lastName+" Middle Name "+ middle +"";
}*/
}
This is my Student class:
public class Student {
private int studentId;
private Name name;
private Address address;
boolean a;
ArrayList<Course> courseSchedule = new ArrayList<Course>();
ArrayList<Student> student=new ArrayList<Student>();
public Student(String fiName,String laName, char middle,int stNumber,String stName,String city,String state,int province,String country,int id)
{
if(student.contains(id))
{
System.out.println("Student cannot be same id");
}
else
{
address= new Address(stNumber,stName,city,state,province,country);
name=new Name(fiName,laName,middle);
this.studentId=id;
student.add();
}
}
public int getID()
{
return studentId;
}
public void setId(int id)
{
this.studentId = id;
}
public ArrayList<Course> getCourseSchedule()
{
return courseSchedule;
}
public void setCourseSchedule(ArrayList<Course> courseSchedule)
{
this.courseSchedule = courseSchedule;
}
public void addCourse(Course c) {
courseSchedule.add(c);
}
public void dropCourse(Course course) {
courseSchedule.remove(course);
}
}
My question is how can you add Student Object into Student ArrayList
and how can I check if the Student Id exists in ArrayList with contains() method
student.contains(id) this line right here it does not seem to be right
I hope im explain my question a little clear now. Sorry for my english also.
You would not keep a list of Student objects within the class for Student. Your ArrayList<Student> student=new ArrayList<Student>(); does not belong there.
You would have another structure or collection kept elsewhere named something like StudentBody. When a student is instantiated, it is added to the StudentBody collection.
List< Student > studentBody = new ArrayList< Student >() ; // This list is stored somewhere else in your app.
You could loop a List of Student objects in the StudentBody object. For each you would access the UniversityId member field and compare to your new one being added.
Or you could use a Map, where the key is a UniversityId object and the value is a Student object. Check for an existing key before adding.
These solutions ignore the important issue of concurrency. But that is likely okay for a homework assignment in a beginning course in programming.
Use A HashMap() for collecting information based on unique Ids.
public class Student {
private int studentId;
private Name name;
private Address address;
private static HashMap<Integer,Student> students = new ConcurrentHashMap<>(); // Make a static Map so all objectrs shared same data
public Student(String fiName,String laName, char middle,int stNumber,String stName,String city,String state,int province,String country,int id)
{
if(students.contains(id))
{
System.out.println("Student can be same id");
}
else
{
address= new Address(stNumber,stName,city,state,province,country);
name=new Name(fiName,laName,middle);
this.studentId=id;
students.put(id,this); // use this to add current object
}
}

How can I create a instance of a class with an array of Strings as the only instance variable?

I have written a class Form. An array of 10 Strings is the only parameter in the constructor. How can I create an instance of the class? I'm sure there are other problems in my setters and getters but I cant test them until I fix this.
public class FormLab {
public static void main(String[]args){
Form f1 = new Form(String webForm);
System.out.println(print(String[] webForm));
System.out.println("Any Empty Strings? " + f1.getEmptyFields);
System.out.println("Number of characters in userID? " + f1.getCharNum);
System.out.println("Do password fields match? " + f1.getPwCheck);
System.out.println("Does email contain correct characters? " + f1.getEmailCheck);
}
}
public class Form {
String[] webForm = new String[10];
private String userID;
private String pw;
private String pw2;
private String email;
private String name;
private String address;
private String city;
private String state;
private String zip;
private String telephone;
//constructor
public Form(String[] webForm){
//filling array with field values
webForm[0] = "0123456789";
webForm[1] = "java123";
webForm[2] = "java123";
webForm[3] = "luke.skywalker#jedi.com";
webForm[4] = "Luke Skywalker";
webForm[5] = "1234 The Force Way";
webForm[6] = "Rome";
webForm[7] = "GA";
webForm[8] = "30161";
webForm[9] = "7065551234";
}
public boolean getEmptyFields() {
//boolean empty = false;
for(int i = 0; i < webForm.length; i++){
if(webForm[i]!= null){
return true;
}
}
return false;
}
public String getUserID(){
return userID;
}
public void setUserId(String userID){
this.userID = userID;
}
public String getPw(){
return pw;
}
public void setPw(String pw){
this.pw = pw;
}
public String getPw2(){
return pw2;
}
public void setPw2(String pw2){
this.pw2 = pw2;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address = address;
}
public String getCity(){
return city;
}
public void setCity(String city){
this.city = city;
}
public String getState(){
return state;
}
public void setState(String state){
this.state = state;
}
public String getZip(){
return userID;
}
public void setZip(String zip){
this.zip = zip;
}
public String getTelephone(){
return telephone;
}
public void setTelephone(String telephone){
this.telephone = telephone;
}
public int getCharNum(String userID) {
int userLength = 0;
//userID.length();
return userLength;
}
public boolean getPwCheck() {
boolean check = pw.equalsIgnoreCase(pw2);
// pw.equalsIgnoreCase(pw2);
return check;
}
public boolean getEmailCheck(String email) {
if(email.contains("#") && email.contains(".")){
return true;
}
return false;
}
public static void getPrint(String[] webForm) {
System.out.println(webForm.toString());
}
}
Use method arraycopy.
public Form(String[] webForm){
System.arraycopy(webForm, 0, this.webForm, 0, webForm.length);
}
The constructor takes a string array as argument, but you are passing it a string, try:
myList = new String[];
myForm = new Form(myList);
You need to declare your array before putting it as a parameter as follow:
public class FormLab {
public static void main(String[]args){
String webForm = new String[10];
Form f1 = new Form(webForm);
/*System.out.println(print(String[] webForm)); THIS IS WRONG*/
/*TO PRINT THE VALUES IN THE ARRAY YOU NEED TO WRITE A METHOD IN UR
FORM CLASS THAT WILL LOOP THRU UR VARIABLE AND PRINT*/
System.out.println("Any Empty Strings? " + f1.getEmptyFields);
System.out.println("Number of characters in userID? " + f1.getCharNum);
System.out.println("Do password fields match? " + f1.getPwCheck);
System.out.println("Does email contain correct characters? " + f1.getEmailCheck);
}

Make object array of sub-class

So it seems like I have to make an object array of a sub-class (Bicycle).
I then add two objects to this.. and loop the array and print what each object is constructed from.
This sounds thoroughly confusing to me, and I'm unsure how to go about this.
I'll also post the rest of my code, to make more sense.
MAIN:
package javaapplication4;
public class JavaApplication4 {
public static void main(String[] args) {
Bicycle myBike = new Bicycle(1, "Haro BMX", true, "Handlebars, Tyres, Frame");
System.out.println(myBike);
}
}
package javaapplication4;
public class Implement {
String name;
boolean hasMovingParts;
String constructedFrom;
public Implement() {
}
public Implement(String name, boolean hasMovingParts, String constructedFrom) {
this.name = name;
this.hasMovingParts = hasMovingParts;
this.constructedFrom= constructedFrom;
}
public String getName() {
return name;
}
public boolean getMovingParts() {
return hasMovingParts;
}
public String getConstructedFrom(){
return constructedFrom;
}
public class Bicycle extends Implement {
public int seatNumber;
public Bicycle(int seatNumber, String name, boolean hasMovingParts, String constructedFrom) {
this.seatNumber = seatNumber; //takes the value you pass as parameter
this.name = name; // and stores it into the instance variable
this.hasMovingParts = hasMovingParts;
this.constructedFrom = constructedFrom;
}
#Override
public String toString(){
return String.format("*Vehicle Statistics* Seats: %d, Name:" +
" %s, Contains Moving Parts: %b, Materials: %s",
seatNumber, name, hasMovingParts, constructedFrom);
}
}
}
package javaapplication4;
public class Bicycle extends Implement {
public int seatNumber;
public Bicycle(int seatNumber, String name, boolean hasMovingParts, String constructedFrom) {
this.seatNumber = seatNumber;
this.name = name;
this.hasMovingParts = hasMovingParts;
this.constructedFrom = constructedFrom;
}
#Override
public String toString() {
return String.format("*Vehicle Statistics* Seats: %d, Name:" +
" %s, Contains Moving Parts: %b, Materials: %s",
seatNumber, name, hasMovingParts, constructedFrom);
}
}
Change your main method to create an array of Bicycles, then add them by the index :
public static void main(String[] args) {
Bicycle[] bicycles = new Bicycle[2];
bicycles[0] = new Bicycle(1, "Haro BMX", true, "Handlebars, Tyres, Frame");
bicycles[1] = new Bicycle(1, "Orah XMB", true, "Handlebars, Tyres, Frame");
for (Bicycle bicycle : bicycles){
System.out.println(bicycle);
}
}

How to add value from another class (java)

I have two classes: profesor and subject
public class Profesor {
private int numbClassroom;
public Profesor(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public int getNumbClassroom() {
return numbClassroom;
}
public void setNumbClassroom(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public String ToString(){
return "Number of classroom: "+numbClassroom;
} }
The second class is:
public class Subject{
String name;
Profesor lecturer = new Profesor();
Date yearOfStudy;
public void Dodeli(Profesor p){
??????
}}
I do not know how to add professor like a lecturer to a current subject
Like this? I don't see any problem.
public void Dodeli(Profesor p){
lecturer = p;
}
Profesor lecturer = new Profesor();
No need to instantiate lecturer. Just declare it. Then have getter/setter methods for it
Then you can assign Professor to Subject
Subject subj = new Subject("OOP"); //assuming you have corresponding constructor
subj.setLecturer(new Professor()); //or if you have existing prof object
Maybe require something like this : try to encapsulate your code
public class Professor {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Subject{
private String name;
private Professor professor;
private int numbClassroom;
private Date yearOfStudy;
public int getNumbClassroom() {
return numbClassroom;
}
public void setNumbClassroom(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Professor getProfesor() {
return professor;
}
public void setProfesor(Professor profesor) {
this.professor = profesor;
}
public void Dodeli(){
System.out.println("Pofessor "+getProfesor().getName()+" is teaching "+getName()+" in Room NO :"+getNumbClassroom());
}
}
public class TestImpl {
public static void main(String arr[])
{
Subject subject = new Subject();
Professor professor = new Professor();
subject.setName("Biology");
professor.setName("MR.X");
subject.setNumbClassroom(1111);
subject.setProfesor(professor);
subject.Dodeli();
}
}

How to create a roster of students in java

I have a homework assignment problem that looks like this:
(20 pts) Create a Student class with the following:
A private String variable named “name” to store the student’s name
A private integer variable named “UFID” that contains the unique ID number for this student
A private String variable named “DOB” to store the student’s date of birth
A private integer class variable named numberOfStudents that keeps track of the number of students that have been created so far
A public constructor Student(String name, int UFID, String dob)
Several public get/set methods for all the properties
getName/setName
getUFID/setUFID
getDob/setDob
Write a test program, roster.java, that keeps a list of current enrolled students. It should have methods to be able to enroll a new
student and drop an existing student.
I'm not asking anyone to do this assignment for me, I just really need some general guidance. I think I have the Student class pretty well made, but I can't tell exactly what the addStudent() and dropStudent() methods should do - should it add an element to an array or something or just increments the number of students? The code I have so far looks like this.
public class Student {
private String name;
private int UFID;
private String DOB;
private static int numberOfStudents;
public Student(String name, int UFID, String DOB) {
this.name = name;
this.UFID = UFID;
this.DOB = DOB;
}
public String getDOB() {
return DOB;
}
public void setDOB(String dOB) {
DOB = dOB;
}
public int getUFID() {
return UFID; }
public void setUFID(int uFID) {
UFID = uFID; }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public void setNumberOfStudents(int numberOfStudents) {
Student.numberOfStudents = numberOfStudents;
}
public static void addStudent(String name, int UFID, String DOB) {
numberOfStudents++;
}
public static void dropStudent(String name) {
numberOfStudents--;
}
}
Any guidance as I finish this up would be greatly appreciated.
The assignment writes itself: you need a Roster class that owns and maintains a collection of Students:
public class Roster {
private Set<Student> roster = new HashSet<Student>();
public void addStudent(Student s) { this.roster.add(s); }
public void removeStudent(Student s) { this.roster.remove(s); }
}

Categories