array in a separate class other than main method/class - java

I keep getting this error, its about needing braces after the array decleration.
I do not know what to do about this. I want to make an array that is not in my main method. I want the array to be supertype populated with subclass.
Here is my code
public class ArrayTest {
Employee [] employees = new Manager[2];
employees[0]= new Manager("Thomas", "Cummings");
}
public class Manager extends Employee{
private int employees;
public Manager() {
super();
employees = 0;
}
public Manager(int employees) {
super();
this.employees = employees;
}
public Manager(String f_name, String l_name) {
super(f_name, l_name);
}
public Manager(String f_name, String l_name, int employees) {
super(f_name, l_name);
this.employees = employees;
}
public int getEmployees() {
return employees;
}
public void setEmployees(int employees) {
this.employees = employees;
}
public void setManager(String f_name, String l_name){
this.setF_name(f_name);
this.setL_name(l_name);
}
public void setManager(String f_name, String l_name, int employees){
this.setF_name(f_name);
this.setL_name(l_name);
this.employees = employees;
}
#Override
public String toString(){
return "\nName " + getF_name() + " " + getL_name() +
"\nEmployee ID " + getEmp_id() +
"\nNum of employees " + getEmployees();
}
}
public class Employee {
private String f_name, l_name;
private static long emp_id = 001;
public Employee(){
f_name = "";
l_name = "";
emp_id ++;
}
public Employee(String f_name, String l_name) {
this.f_name = f_name;
this.l_name = l_name;
emp_id ++;
}
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
public long getEmp_id() {
return emp_id;
}
public void setEmp_id(long emp_id) {
Employee.emp_id = emp_id;
}
public String toString(){
return "\nName " + getF_name() + " " + getL_name() +
"\nEmployee ID " + getEmp_id();
}
}

The reason of error is the following statement:
employees[0]= new Manager("Thomas", "Cummings");
as you cannot put executable statements outside of code blocks(methods, blocks, constructors) in a java class.
One way to resolve this problem is by moving the initialization statement in a constructor:
public class ArrayTest {
Employee [] employees = new Manager[2];
public ArrayTest() {
employees[0]= new Manager("Thomas", "Cummings");
}
}

employees[0]= new Manager("Thomas", "Cummings");
this is an statement which needs to be placed in proper executable block (method, constructor, initialization block)

Related

How do I leverage a json mapping file to convert from one pojo to another pojo?

I have two POJOs (Person.java and User.java) that contain similar information. See below:
public class Person {
private String first_name;
private String last_name;
private Integer age;
private Integer weight;
private Integer height;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
}
public class User {
private String name_first;
private String name_last;
private Integer my_age;
private Integer my_weight;
private String social_security;
public String getName_first() {
return name_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public String getName_last() {
return name_last;
}
public void setName_last(String name_last) {
this.name_last = name_last;
}
public Integer getMy_age() {
return my_age;
}
public void setMy_age(Integer my_age) {
this.my_age = my_age;
}
public Integer getMy_weight() {
return my_weight;
}
public void setMy_weight(Integer my_weight) {
this.my_weight = my_weight;
}
public String getSocial_security() {
return social_security;
}
public void setSocial_security(String social_security) {
this.social_security = social_security;
}
}
I have defined a mapping.json file as shown below using GSON.
{
"columnMap": [
{
"userColumn": "name_first",
"personColumn": "first_name"
},
{
"userColumn": "last_first",
"personColumn": "first_last"
},
{
"userColumn": "my_age",
"personColumn": "age"
},
{
"userColumn": "my_weight",
"personColumn": "weight"
}
]
}
public class Mapping {
private ArrayList<Pair> columnMap;
public Mapping(){
columnMap = new ArrayList<>();
}
public ArrayList<Pair> getColumnMap() {
return columnMap;
}
public void setColumnMap(ArrayList<Pair> columnMap) {
this.columnMap = columnMap;
}
}
I am writing a utility class helper function that converts between a Person and User object the mapped pairs.
public class Pair {
private String userColumn;
private String personColumn;
public String getUserColumn() {
return userColumn;
}
public void setUserColumn(String userColumn) {
this.userColumn = userColumn;
}
public String getPersonColumn() {
return personColumn;
}
public void setPersonColumn(String personColumn) {
this.personColumn = personColumn;
}
public static void main(String args[]){
}
}
My question is below:
As you can see the returnVal object is being set by me (the programmer) to convert from a User POJO to a Person POJO. How do I leverage the pre-defined mapping.json to do this? The reason I am asking is in the future, the mapping.json file may change (maybe the weight mapping no longer exists). So I am trying to avoid re-programming this Utility.userToPerson() function. How can I achieve this? I am thinking Java reflection is the way to go, but I would like to hear back from the Java community.
public class Utility {
public static Person userToPerson(User u){
Person returnVal = new Person();
returnVal.setAge(u.getMy_age()); // <-- Question How do I leverage mapping.json here?
returnVal.setFirst_name(u.getName_first());
returnVal.setLast_name(u.getName_last());
returnVal.setWeight(u.getMy_weight());
return returnVal;
}
}
You can introspect the beans (i.e. User and Person) for the field names and call corresponding getter from User to fetch the value. Later call corresponding setter in Person.
Here I have taken userToPersonFieldsMap for mapping the field, you can load mapping from JSON file and construct the map accordingly.
Important code section is the for loop, where it dynamically calls getter and setter and does the job.
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class UserToPersonMapper {
public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
Map<String, String> userToPersonFieldsMap = new HashMap<>();
userToPersonFieldsMap.put("name_first", "first_name");
userToPersonFieldsMap.put("last_first", "first_last");
userToPersonFieldsMap.put("age", "personAge");
//existing user
User user = new User("Tony", "Stark", 20);
//new person - to be initialised with values from user
Person person = new Person();
for (Map.Entry<String, String> entry : userToPersonFieldsMap.entrySet()) {
Object userVal = new PropertyDescriptor(entry.getKey(), User.class).getReadMethod().invoke(user);
new PropertyDescriptor(entry.getValue(), Person.class).getWriteMethod().invoke(person, userVal);
}
System.out.println(user);
System.out.println(person);
}
}
class User {
private String name_first;
private String last_first;
private int age;
public User(String name_first, String last_first, int age) {
this.name_first = name_first;
this.last_first = last_first;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName_first() {
return name_first;
}
public String getLast_first() {
return last_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public void setLast_first(String last_first) {
this.last_first = last_first;
}
#Override
public String toString() {
return "User{" +
"name_first='" + name_first + '\'' +
", last_first='" + last_first + '\'' +
", age=" + age +
'}';
}
}
class Person {
private String first_name;
private String first_last;
private int personAge;
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public void setFirst_last(String first_last) {
this.first_last = first_last;
}
public String getFirst_name() {
return first_name;
}
public String getFirst_last() {
return first_last;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
#Override
public String toString() {
return "Person{" +
"first_name='" + first_name + '\'' +
", first_last='" + first_last + '\'' +
", personAge=" + personAge +
'}';
}
}
You can tweak and try it out this example to make it more align with your requirement.
Note:
This solution uses reflection.

Using toString() method from child class

Hi I am writing a code using polymorphism and I would like to print List on the screen but when I am using my code it run toString method from parent class only. How can I fix it?
public class HospitalApp {
public static void main(String[] main){
Hospital hospital = new Hospital();
List<Person> lista = new ArrayList<>();
lista = hospital.showList();
StringBuilder stringBuilder = new StringBuilder();
for(Person person : lista){
stringBuilder.append(person);
stringBuilder.append("\n");
}
System.out.println(stringBuilder.toString());
}
}
public class Hospital{
List<Person> lista = new ArrayList<>();
Person doktor = new Doctor("All", "Bundy",100, 99999);
Person nurse = new Nurse("Iga", "Lis",160, 10);
Person nurse_1 = new Nurse("Magda", "Andrych",160, 20);
public List showList(){
lista.add(doktor);
lista.add(nurse);
lista.add(nurse_1);
return lista;
}
}
public class Person{
private String imie;
private String nazwisko;
private double wyplata;
public Person(){}
public Person(String imie, String nazwisko, double wyplata){
this.imie = imie;
this.nazwisko = nazwisko;
this.wyplata = wyplata;
}
public void setImie(String imie){
this.imie = imie;
}
public String getImie(){
return imie;
}
public void setNazwisko(String nazwisko){
this.nazwisko = nazwisko;
}
public String getNazwisko(){
return nazwisko;
}
public void setWyplata(double wyplata){
this.wyplata = wyplata;
}
public double getWyplata(){
return wyplata;
}
public String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata();
}
}
public class Nurse extends Person{
private int nadgodziny;
public Nurse(){}
public Nurse(String imie, String nazwisko, double wyplata, int nadgodziny){
super(imie, nazwisko, wyplata);
this.nadgodziny = nadgodziny;
}
public void setNadgodziny(int nadgodziny){
this.nadgodziny = nadgodziny;
}
public int getNadgodziny(){
return nadgodziny;
}
#Override
String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata() + " " + getNadgodziny();
}
}
public class Doctor extends Person {
private double premia;
public Doctor(){}
public Doctor(String imie, String nazwisko, double wyplata , double premia){
super(imie, nazwisko, wyplata);
this.premia = premia;
}
public double getPremia(){
return premia;
}
public void setPremia(double premia){
this.premia = premia;
}
#Override
String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata() + " " + getPremia();
}
}
Can someone help me solve this problem?
The problem lies here, in the Person and Doctor class:
#Override
String toString(){
return ...;
}
you are missing the public specifier. There should be an error / warning about that. Apply it to the method signatures and your code will work as you expect it to.
probably you should add to the List not a Person (object) but a value returned by its toString method:
for(Person person : lista){
stringBuilder.append(person.toString);
stringBuilder.append("\n");
}

Print all elements of Array list [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
i want to print all elements of my array list. Eclipse does not show an error, but it doesnt show the elements that i added in console. Can you please tell me what i did wrong?
The console shows:
Typ:Droide
ID:8282
NameR2D2
HumanoiderRoboter#15db9742
HumanoiderRoboter#6d06d69c
HumanoiderRoboter#7852e922
HumanoiderRoboter#4e25154f
Roboter Class:
public class Roboter {
protected String Name;
protected int ID;
protected String typ;
public Roboter(String Name, int ID, String typ) {
super();
this.Name = Name;
this.ID = ID;
this.typ = typ;
}
public void ausgebenNeu() {
System.out.println("ID:"+ID);
System.out.println("Name:"+Name);
System.out.println("Typ:"+typ);
}
HumanoiderRoboter Class:
import java.util.ArrayList;
public class HumanoiderRoboter extends Roboter {
String RoboterTyp;
public HumanoiderRoboter (String Name, int ID, String typ) {
super(Name, ID, typ);
}
public void ausgeben() {
ArrayList<HumanoiderRoboter> Sensoren = new ArrayList<HumanoiderRoboter>();
Sensoren.add(new HumanoiderRoboter("Sensor1", 4232, "Infrarotsensor"));
Sensoren.add(new HumanoiderRoboter("Sensor2", 9232, "Lichtsensor"));
Sensoren.add(new HumanoiderRoboter("Sensor3", 5777, "Touchssensor"));
Sensoren.add(new HumanoiderRoboter("Sensor4", 3321, "Gyrosensor"));
System.out.println("Typ:" + typ);
System.out.println("ID:" + ID);
System.out.println("Name" + Name);
for (Roboter ele : Sensoren) {
System.out.println(ele);
}
}
public static void main(String[] args) {
HumanoiderRoboter R2 = new HumanoiderRoboter("R2D2", 8282, "Droide");
R2.ausgeben();
}
}
Currently your problem is the HumanoiderRoboter doesn't overwrite the toString method which results the HumanoiderRoboter#4e25154f stuff. So if you overwrite the toString method it will print your object stuff you put in there:
...
#Override
public String toString() {
return "Typ: " + type + ", ID: " + id + ", Name: " + name;
}
...
Default toString method from Object looks like that:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So now if you do System.out.println(theObject) it will for example result something like this:
Typ: some, ID: 5, Name: NiceRoboter
And if you want the complete array as one String you can use the Arrays#toString method:
System.out.println(Arrays.toString(yourList.toArray()));
In your Roboter class override toString() method like this:
public class Roboter {
//-----member fields,methods
//Add this method
#Override
public String toString(){
return "{name:"+this.Name+"}";
}
}
Also read this link for naming convention to follow in Java https://www.geeksforgeeks.org/java-naming-conventions/
Override toString() method in Roboter class.
public class Test extends Roboter {
String RoboterTyp;
public Test(String Name, int ID, String typ) {
super(Name, ID, typ);
}
public void ausgeben() {
ArrayList<Test> Sensoren = new ArrayList<Test>();
Sensoren.add(new Test("Sensor1", 4232, "Infrarotsensor"));
Sensoren.add(new Test("Sensor2", 9232, "Lichtsensor"));
Sensoren.add(new Test("Sensor3", 5777, "Touchssensor"));
Sensoren.add(new Test("Sensor4", 3321, "Gyrosensor"));
System.out.println("Typ:" + typ);
System.out.println("ID:" + ID);
System.out.println("Name" + Name);
for (Roboter ele : Sensoren) {
System.out.println(ele);
}
}
public static void main(String[] args) {
Test R2 = new Test("R2D2", 8282, "Droide");
R2.ausgeben();
}
}
public class Roboter {
String Name;
int ID;
String typ;
public Roboter(String name, int iD, String typ) {
super();
Name = name;
ID = iD;
this.typ = typ;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getTyp() {
return typ;
}
public void setTyp(String typ) {
this.typ = typ;
}
#Override
public String toString() {
return "Roboter [Name=" + Name + ", ID=" + ID + ", typ=" + typ + "]";
}
}

Make a JTable in Swing with Response of GET REST Webservices

i have a Swing App, i use Retrofit to Consume Rest Service in my Swing App.
Now I want to Populate the Response of m Get Service in a Jtable.
Thais the List for all Employees that i get using Retrofit
ArrayList<Employee> employees = EmployeesData.getInstance().getEmployees();
I want to Populate that in a Jtable
That is My Employee Modell
public class Employee {
private long empno;
private String ename;
private String job;
private Date hiredate;
private long mgr;
private long sal;
private long deptno;
public long getEmpno() {
return empno;
}
public void setEmpno(long empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public long getMgr() {
return mgr;
}
public void setMgr(long mgr) {
this.mgr = mgr;
}
public long getSal() {
return sal;
}
public void setSal(long sal) {
this.sal = sal;
}
public long getDeptno() {
return deptno;
}
public void setDeptno(long deptno) {
this.deptno = deptno;
}
#Override
public String toString() {
return empno + " \t"
+ ename + " \t"
+ deptno + " \t"
+ mgr + " \t"
+ sal + " \t"
+ hiredate.toString();
}
}
Here i want to Populate the Table
public void updateConsole() {
ArrayList<Employee> employees = EmployeesData.getInstance().getEmployees();
StringBuilder builder = new StringBuilder();
for (Employee employee : employees) {
builder.append(employee.toString());
columns.add("col1");
columns.add("col2");
columns.add("col3");
TableModel tableModel = new DefaultTableModel(employees.toArray(new Object[][] {}), columns.toArray());
table = new JTable(tableModel);
builder.append("\n");
}
textPane.setText(builder.toString());
}
And i have that Error
java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays.copyOf(Arrays.java:3213)
at java.util.ArrayList.toArray(ArrayList.java:407)
at View.Console.updateConsole(Console.java:43)
at application.Main.updateConsole(Main.java:54)
Somebody can help me please?
it Works fine now. I make it like so
public void updateConsole() {
ArrayList<Employee> employees = EmployeesData.getInstance().getEmployees();
Object[] columnNames = { "Deptno", "Empno", "Name","Hiredate","Job","Management","Salary"};
DefaultTableModel model = new DefaultTableModel(new Object[0][0], columnNames);
StringBuilder builder = new StringBuilder();
for (Employee employee : employees) {
//builder.append(employee.toString());
Object[] o = new Object[7];
o[0] = employee.getDeptno();
o[1] = employee.getEmpno();
o[2] = employee.getEname();
o[3] = employee.getHiredate();
o[4] = employee.getJob();
o[5] = employee.getMgr();
o[6] = employee.getSal();
model.addRow(o);
//builder.append("\n");
}
//textPane.setText(builder.toString());
table.setModel(model);
}

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.

Categories