Java Packages Concepts - java

Person.java
package A;
public class Person {
public String name , surname;
public Person() {
name = " Unknown ";
surname = " Unknown ";
}
public Person(String n , String s) {
name = n;
surname = s;
}
public Person(Person p1) {
name = p1.name;
surname = p1.surname;
}
}
ContactInfo.java
package A.B;
import A.Person;
public class ContactInfo extends Person {
public String phone;
public ContactInfo() {
phone = "Unvalid ";
}
public ContactInfo(String n , String s , String phn) {
super(n,s);
phone = phn;
}
public ContactInfo(ContactInfo ci) {
super(ci);
phone = ci.phone;
}
}
Employee.java
package A.B.C;
import A.B.ContactInfo;
public class Employee extends ContactInfo {
int salary;
public Employee() {
salary = 0;
}
public Employee(String n , String s , String phn ,int sal) {
super(n,s,phn);
salary = sal;
}
public Employee(Employee e) {
super(e);
salary = e.salary;
}
public void show() {
System.out.println("Name: "+name+surname+ " Phone: "+phone+ " Salary: "+salary);
}
}
Office.java
//import A.B.C.Employee;
import A.B.C.*;
class Office {
public static void main(String args[]) {
Employee e1 = new Employee();
System.out.println();
e1.show();
Employee e2 = new Employee(" John "," Snow "," 001122 ",123);
System.out.println();
e2.show();
Employee e3 = new Employee(e2);
System.out.println();
e3.show();
}
}
As in Office.java file when i using this statment : import A.B.C.Employee;
it will shows the desired output but when i using : import
A.B.C.*; it will shows errors. Why it is always fails to get the correct path?
Little help is needed to understand it .

Related

Inheritance and arrays in Java

I have a class look like this:
public class People {
private String Name;
private String Address;
public People(String aName, String aAddress) {
this.Name=aName;
this.Address=aAddress;
}
public String getName() {
return Name;
}
public String getAddress() {
return Address;
}
void display() {
System.out.println("Name:\t"+Name);
System.out.println("Address:\t" +Address);
}
}
and another 2:
class Students extends People{
private int MatriculationNumber;
private String CourseName;
public Students (String aName, String aAddress, int matriculationNumber, String courseName){
super(aName,aAddress);
this.MatriculationNumber=matriculationNumber;
this.CourseName=courseName;
}
void display() {
super.display();
System.out.println("Matriculation Number: \t" +MatriculationNumber);
System.out.println("Course Name: \t" +CourseName);
}
}
class Staffs extends People{
private int EmployeeNumber;
private String Department;
public Staffs (String aName, String aAddress, int employeeNumber, String department){
super(aName,aAddress);
this.EmployeeNumber=employeeNumber;
this.Department=department;
}
void display() {
super.display();
System.out.println("Employee Number: \t" +EmployeeNumber);
System.out.println("Department: \t" +Department);
}
}
The question is how to create a class named "School" which have a List can contain both Students and Staffs, so I can add a method like AddPeople() which can add or remove Students or Staffs from it?
You can use the below solution. The solution is not thread-safe but should work fine for your usecase.
import java.util.ArrayList;
class School {
private List<People> peopleList = new ArrayList<People>();
public void addPeople(People people) {
peopleList.add(people);
}
public void removePeople(People people) {
peopleList.remove(people);
}
public static void main(String... args) {
Student student = new Student("Name", "Address", 90, "Course");
Staff staff = new Staff("Name", "Address", 1001, "Department");
School school = new School();
school.addPeople(student);
school.addPeople(staff);
school.removePeople(student);
school.removePeople(staff);
}
}
You can create a new Staff Class which also extends from the People Class
package so;
public class Staff extends People {
public Staff(String aName,String aAddress) {
super(aName, aAddress);
}
}
Then give as type of your list the base class People.
package so;
import java.util.ArrayList;
import java.util.List;
public class School {
List<People> peopleContainer = new ArrayList<People>();
public void addPeople(People p){
this.peopleContainer.add(p);
}
public void removePeople(People p) {
this.peopleContainer.remove(p);
}
public void displayPeople() {
for(People person : peopleContainer) {
person.display();
}
}
}
Then you can add staff and student objects to your list and also all other objects which classes extends from people or even people objects itself.
package so;
public class Main {
public static void main(String[] args) {
Students stud1 = new Students("Max", "MustermanAddress", 181242, "CS50");
Staff staff1 = new Staff("Christian", "AugustAddress");
School school = new School();
school.addPeople(stud1);
school.addPeople(staff1);
school.displayPeople();
school.removePeople(staff1);
System.out.println();
System.out.println();
school.displayPeople();
}
}
Output will be
Name: Max
Address: MustermanAddress
Matriculation Number: 181242
Course Name: CS50
Name: Christian
Address: AugustAddress
Name: Max
Address: MustermanAddress
Matriculation Number: 181242
Course Name: CS50

how to get input for an array of class in java?

I am new in java and I trying to get information
for five students and save them into an array of classes. how can I do this?
I want to use class person for five students whit different informations
import java.io.IOException;
import java.util.*;
public class exam
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
// I want to get and save information in this array
person[] f = new student[5];
}
}
class person defined for get name and family name.
import java.util.*;
public abstract class person {
Scanner scr = new Scanner(System.in);
private String name , fname;
public void SetName() {
System.out.println("enter name and familyNAme :");
name = scr.next();
}
public String getname() {
return name;
}
public void setfname () {
System.out.println("enter familyname:");
fname = scr.next();
}
public String getfname() {
return fname;
}
}
class student that inherits from the class person for get studentID and student Scores .
import java.util.*;
class student extends person {
float[] p = new float[5];
int id , sum ;
float min;
public void inputs() {
System.out.println("enter the id :");
id = scr.nextInt();
}
public void sumation() {
System.out.println("enter points of student:");
sum= 0;
for(int i = 0 ; i<5 ; i++){
p[i]=scr.nextFloat();
sum+=p[i];
}
}
public void miangin() {
min = (float)sum/4;
}
}
So first things first, when creating Java objects, refrain from getting input inside the object so that if you decide to change the way you get input (e.g. transition from command line to GUI) you don't need to modify the Java object.
Second, getters and setters should only get or set. This would save some confusion when debugging since we don't have to check these methods/functions.
So here's the person object:
public abstract class Person {
protected String name, fname;
public Person (String name, String fname) {
this.name = name;
this.fname = fname;
}
public void setName (String name) {
this.name = name;
}
public String getName () {
return name;
}
public void setFname (String fname) {
this.fname = fname;
}
public String getFname () {
return fname;
}
}
And here's the student object (tip: you can make as much constructors as you want to make object creation easier for you):
public class Student extends Person {
private float[] p;
private int id;
public Student (String name, String fname) {
this (name, fname, -1, null);
}
public Student (String name, String fname, int id, float[] p) {
super (name, fname);
this.id = id;
this.p = p;
}
public void setP (float[] p) {
this.p = p;
}
public float[] getP () {
return p;
}
public void setId (int id) {
this.id = id;
}
public int getId () {
return id;
}
public float summation () {
float sum = 0;
for (int i = 0; i < p.length; i++)
sum += p[i];
return sum;
}
public float miangin () {
return summation () / 4.0f;
}
#Override
public String toString () {
return new StringBuilder ()
.append ("Name: ").append (name)
.append (" Family name: ").append (fname)
.append (" Id: ").append (id)
.append (" min: ").append (miangin ())
.toString ();
}
}
And lastly, wherever your main method is, that is where you should get input from. Take note that when you make an array, each index is initialized to null so you still need to instantiate each array index before using. I made a sample below but you can modify it depending on what you need.
import java.util.*;
public class Exam {
Scanner sc;
Person[] people;
Exam () {
sc = new Scanner (System.in);
people = new Person[5];
}
public void getInput () {
for (int i = 0; i < people.length; i++) {
System.out.print ("Enter name: ");
String name = sc.nextLine ();
System.out.print ("Enter family name: ");
String fname = sc.nextLine ();
System.out.print ("Enter id: ");
int id = sc.nextInt (); sc.nextLine ();
System.out.println ("Enter points: ");
float[] points = new float[5];
for (int j = 0; j < points.length; j++) {
System.out.printf ("[%d] ", j + 1);
points[j] = sc.nextFloat (); sc.nextLine ();
}
people[i] = new Student (name, fname, id, points);
}
}
public void printInput () {
for (Person p: people)
System.out.println (p);
}
public void run () {
getInput ();
printInput ();
}
public static void main (String[] args) {
new Exam ().run ();
}
}
Just one last tip, if you ever need dynamic arrays in Java, check out ArrayList.
You can add a class attribute, and then add class information for each student, or you can add a class class, define an array of students in the class class, and add an add student attribute, and you can add students to that class.
First of all, please write class names with capital letter (Student, Exam <...>).
Exam class:
import java.util.Scanner;
public class Exam {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[]{
new Student(),
new Student(),
new Student(),
new Student(),
new Student()
};
for (int i = 0; i < 5; i++) {
students[i].setFirstName();
students[i].setLastName();
students[i].setId();
}
}
}
Person class:
import java.util.Scanner;
public class Person {
String firstName, lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName() {
System.out.println("Type firstName: ");
this.firstName = new Scanner(System.in).next();
}
public String getLastName() {
return lastName;
}
public void setLastName() {
System.out.println("Type lastName: ");
this.lastName = new Scanner(System.in).next();
}
}
Student class:
import java.util.Scanner;
public class Student extends Person{
int id;
public int getId() {
return id;
}
public void setId() {
//Converting String line into Integer by Integer.parseInt(String s)
System.out.println("Type id: ");
this.id = Integer.parseInt(new Scanner(System.in).next());
}
}

Need various ways to come up with this output

I am supposed to come up with this output.
But I am getting this instead..
Here is my code:
import java.lang.*;
import java.util.*;
import java.io.*;
public class Sample{
private String name;
private Hashtable customers = new Hashtable();
private Hashtable movies = new Hashtable();
public Sample(String aName){
name = aName;
}
public String getName(){
return name;
}
public void setName(String aName){
name = aName;
}
public void addCustomer (Customer customer) {
customers.put(customer.getName(), customer);
}
public Customer getCustomer (String customerName) {
return (Customer)customers.get(customerName);
}
public void addMovie (Movie movie) {
movies.put(movie.getName(), movie);
}
public Movie getMovie (String movieName) {
return (Movie)movies.get(movieName);
}
public void error (String message) {
System.out.println ("ERROR: " + message);
}
public Enumeration getMovies() {
return movies.elements();
}
public Enumeration getCustomers() {
return customers.elements();
}
public void showAll() {
System.out.println ("name: "+ this.getName());
Enumeration kk = this.getCustomers();
while (kk.hasMoreElements()) {
Customer one = (Customer) kk.nextElement();
System.out.println (one.show());
}
Enumeration ff = this.getMovies();
while (ff.hasMoreElements()) {
Movie one = (Movie) ff.nextElement();
System.out.println (one.show());
}
}
public void test() {
Customer k1 = new Customer ("Jonah") ; this.addCustomer (k1);
Customer k2 = new Customer ("Hellen") ; this.addCustomer (k2);
Customer k3 = new Customer ("Agnes") ; this.addCustomer (k3) ;
Movie f1 = new Movie ("StarWars"); this.addMovie (f1) ;
Movie f2 = new Movie ("Shrek"); this.addMovie (f2) ;
System.out.println("-**-**- test part 1 -**-**-") ;
this.showAll();
System.out.println("-**-**- test part 2 -**-**-") ;
System.out.println("---" + k1.getName() + " rents " + f1.getName());
this.showAll();
k1.doRent(f1);
MY CUSTOMER CLASS:
package eric;
public class Customer {
String name;
public Customer(String nameCus){
name = nameCus;
}
public String getName(){
return name;
}
public String show(){
return name;
}
public void doRent(Movie f1) {
System.out.println(" -"+ " RentData" + "[" + getName() +"," + f1.getName() + "]" );
}
}
MY MOVIE CLASS:
public class Movie {
String name;
int x = 0;
public Movie(String nameMov){
name = nameMov;
}
public String getName(){
return name;
}
public String show(){
return name+"\n"+" - average: "+x +" days\n"+" - number of rentings: "+x ;
}
}
My problem is that i cannot find a way to fix -RentData [Jonah,StarWars] under the name Jonah... Instead it comes at the end of output.. I need some one to help me figure how am ganna do that.. thanks
You're calling k1.doRent(f1) before this.showAll() so naturally you will get the "RentData..." line printed before the names are printed. The way your code is now is not conducive to what you're trying to do at all. Your Customer class should have a member list called rentedMovies that is populated every time you call doRent(...) on a Customer object. Then, Customer.show() should print the name of the customer, followed by your "RentData..." stuff that comes from rentedMovies.

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to asd.Grade

i have a large scale project in my hands but i simulated the problem i'm struggling with in this example:
my first class:
package asd;
import java.io.Serializable;
public class Grade implements Serializable{
String name;
Integer score;
public String getName() {
return name;
}
public Grade() {}
public Grade(String name, Integer score) {
this.name = name;
this.score = score;
}
public void setName(String name) {
this.name = name;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
}
my second class:
package asd;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private Object grade;
public String getName() {
return name;
}
public Student(String name, Object grade) {
this.name = name;
Grade = grade;
}
public Student() {}
public void setName(String name) {
this.name = name;
}
public Object getGrade() {
return Grade;
}
public void setGrade(Object grade) {
Grade = grade;
}
}
and this is my main class:
package asd;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
public class Test {
public static void main(String[] args){
Student s1 = new Student();
s1.setName("JeanPierre");
s1.setGrade(new Grade("Math", 8));
Gson gson = new GsonBuilder().create();
String convertedToJson = gson.toJson(s1);
System.out.println("Json string: " + convertedToJson);
Student s2 = gson.fromJson(convertedToJson, Student.class);
System.out.println("Student Name: " + s2.getName());
System.out.println("Grade Name: " + ((Grade)s2.getGrade()).getName());
System.out.println("Grade Score: " + ((Grade)s2.getGrade()).getScore());
}
}
Output:
Json string is :
{"name":"JeanPierre","Grade":{"name":"Math","score":8}}
Student Name: JeanPierre
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to asd.Grade
at asd.Test.main(Test.java:24)
My problem is when i call:
System.out.println("Grade Name: " + ((Grade)s2.getGrade()).getName());
or
System.out.println("Grade Score: " + ((Grade)s2.getGrade()).getScore());
i get this exception:
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to asd.Grade
at asd.Test.main(Test.java:24)
Declaration and setting of the Grade in Student is syntactically wrong. Not sure how it's even building like that.
public class Student implements Serializable
{
protected String name ;
protected Grade grade ;
public Student( String name, Grade grade )
{
this.setName(name).setGrade(grade) ;
}
public String getName()
{ return this.name ; }
public Student setName( String name )
{
this.name = name ;
return this ;
}
public Grade getGrade()
{ return this.grade ; }
public Student setGrade( Grade grade )
{
this.grade = grade ;
return this ;
}
}
You need to parse the grade class as well. It won't convert the entire complex object in one attempt. Try the below code:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Test {
public static void main(String[] args){
Student s1 = new Student();
s1.setName("JeanPierre");
s1.setGrade(new Grade("Math", 8));
Gson gson = new GsonBuilder().create();
String convertedToJson = gson.toJson(s1);
System.out.println("Json string: " + convertedToJson);
Student s2 = gson.fromJson(convertedToJson, Student.class);
System.out.println("Student Name: " + s2.getName());
Grade g = gson.fromJson(s2.getGrade().toString(), Grade.class);
System.out.println("Grade Name: " + g.getName());
System.out.println("Grade Score: " + g.getScore());
}
}
Here s2.getGrade().toString() is still a valid JSON string. You are converting that to Grade class and using it. This is the right way to parse complex objects. Hope you understood.
I changed everything to XML and using XStream now, which works on my tests. Thanks for everyone's answers.

Java search method between objects using scanner

I am trying to make a program in java oop in which I create some persons in the main (every person has a name, an age, a status: employed or not).
I want to search these persons by name and display all the details.
For example if a have a person named John and I find it by name, I want to list all the details (status, age and so on).
I tried to implement this method in Person class.
I don t know if is better to create a map which contains all the persons and the name and then to search in it.
Below is my code:
Person CLASS:
package app;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Person extends Employed {
Scanner scan = new Scanner(System.in);
private String name;
private int age;
private int kids;
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;
}
public int getKids() {
return kids;
}
public void setKids(int kids) {
this.kids = kids;
}
public Person(){
System.out.println("************************************************************");
}
public void displayPerson(){
if(super.getPeriod()==0 && super.getUnemploymentBenefit()==0){
System.out.println(name + " is " + age + " years old, has " + kids + " kids and is employed" + "\nWorking Place: " + super.getWorkingPlace()
+ "\nSallary: " + df.format(super.getSallary()) + " EUR per year" + "\nWorking Time: " + super.getHours() + " hours per day");
}else
System.out.println(name + " is " + age + " years old, has " + kids + " kids and is unemployed" +"\nUnemployment Time: " + Math.round(super.getPeriod())
+ "\nUnemployment Benefit: " + df.format(super.getUnemploymentBenefit()) + " EUR per year");
}
public void searchMethod(){
System.out.println("Are you looking for someone?");
String s = scan.nextLine();
if(s==name) {
System.out.println("Here are all the details about the person you are looking for: ");
}
}
}
Employed CLASS:
package app;
import java.text.DecimalFormat;
public class Employed extends Unemployed {
DecimalFormat df = new DecimalFormat("0.000");
private String WorkingPlace;
private double sallary;
private double hours;
public String getWorkingPlace() {
return WorkingPlace;
}
public void setWorkingPlace(String WorkingPlace) {
this.WorkingPlace = WorkingPlace;
}
public double getSallary() {
return sallary;
}
public void setSallary(double sallary) {
this.sallary = sallary;
}
public double getHours() {
return hours;
}
public void setHours(double hours) {
this.hours = hours;
}
}
Unemployeed CLASS:
package app;
public class Unemployed{
private double period;
private double UnemploymentBenefit;
public double getPeriod() {
return period;
}
public void setPeriod(double period) {
this.period = period;
}
public double getUnemploymentBenefit() {
return UnemploymentBenefit;
}
public void setUnemploymentBenefit(double UnemploymentBenefit) {
this.UnemploymentBenefit = UnemploymentBenefit;
}
}
Program CLASS:
package app;
public class Program extends Person{
public static void main(String[] args) {
Person p1 = new Person();
p1.setName("John Doe");
p1.setAge(47);
p1.setKids(3);
p1.setWorkingPlace("IKEA");
p1.setSallary(12.500);
p1.setHours(12.5);
p1.displayPerson();
p1.searchMethod();
Person p2 = new Person();
p2.setName("Snow Tiffany");
p2.setAge(27);
p2.setKids(0);
p2.setPeriod(15.9);
p2.setUnemploymentBenefit(7.000);
p2.displayPerson();
}
}
First you should add a construtor.
Then you can create an object from class Person like this:
Person p1 = new Person("John Doe", 47,3, "IKEA", 12.500, 12.5);
String personInfo = p1.get(..) + p1.get(..);
System.out.println(personInfo);
Your code is a bit desorganized. Java classes should have constructors. Variables, in general, starts with lowerCase character.

Categories