How do i store a whole void method in array variable - java

public void body()
String name = "", address = "",checkin = "", checkout = "";
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
for(k =1;;k++)
{
}
I need to store whole method in a array variable at once.
well actually for every loop i want to create a element in array.

Like chrylis said in his comment you could create a class Reservation with the fields you want to store.
public class Reservation {
private String name;
private String address;
private String checkin;
private String checkout;
public Reservation(String name, String address, String checkin, String checkout) {
this.name = name;
this.address = address;
this.checkin = checkin;
this.checkout = checkout;
}
//getters and setters ...
}
Then you can create a new Object of it in your method and add it to your array
ArrayList<Reservation> reservations = new ArrayList<>();
for(k =1;;k++) {
reservations.add(new Reservation(...));
}
I used an ArrayList instead of an Array because you can add as many elements as you want to an ArrayList

Related

Accessing an element inside an Array of an Array

Given the following class:
public class Customer {
protected String firstName;
protected String lastName;
protected String ID;
protected float amountSpent;
// Contructor
// Accessors and mutators
}
public class Gold extends Customer {
protected discount;
// overloaded contructor
// Accessors and mutator
}
and the following code
Customer[][] arr = new Customer[2][1];
Customer[] preferredArr = new Gold[3];
Customer[] regularArr = new Customer[3];
preferredArr[0] = new Gold("John", "Doe", "1234", 45, .12)
regularArr[0] = new Customer("Caroline", "Merritt", "5678", 60)
arr[0] = preferredArr;
arr[1] = regularArr;
How would I access John's information using preferredArr[0].getFirstName() if it is inside of the arr array. Also I can't use ArrayList as specified by my professor. Thanks for the help!
preferredArr[0].getFirstName(), work because the object is in preferredArr. to be exact the reference of the object.
arr[0][0].getFirstName(): also, work, because also, only the reference to the same object is stored in arr[0][0].
class Customer {
protected String firstName;
protected String lastName;
protected String ID;
protected float amountSpent;
// Contructor
Customer(String firstName, String lastName, String ID, float amountSpent)
{
this.firstName = firstName;
this.lastName = lastName;
this.ID = ID;
this.amountSpent = amountSpent;
}
// Accessors and mutators
public String getFirstName()
{
return this.firstName;
}
}
class Gold extends Customer {
protected int discount;
// overloaded contructor
Gold(String firstName, String lastName, String ID, int discount, float amountSpent)
{
super(firstName, lastName, ID, amountSpent);
this.discount = discount;
}
// Accessors and mutator
}
public class Main
{
public static void main(String[] args)
{
Customer[][] arr = new Customer[2][1];
Customer[] preferredArr = new Gold[3];
Customer[] regularArr = new Customer[3];
preferredArr[0] = new Gold("John", "Doe", "1234", 45, 0.12f);
regularArr[0] = new Customer("Caroline", "Merritt", "5678", 60);
arr[0] = preferredArr;
arr[1] = regularArr;
System.out.println("preferredArr[0].getFirstName() = "+preferredArr[0].getFirstName());
System.out.println("arr[0][0].getFirstName() = "+arr[0][0].getFirstName());
}
}
The result :
preferredArr[0].getFirstName() = John
arr[0][0].getFirstName() = John
You can check this : two references to the same object.
And where the object in java are stored
Good Luck.

Why i cannot display element of mine list? - java

i have problem with my list. My goal is to make a JTree from my json list. To do it i convert my json where i have my patients to list. But i cannot even display the name of mine patient. Maybe my code make my problem clearer. I would be grateful for any suggestion!
My patient class:
public class Patient {
private String name;
private String surname;
private String pesel;
public Patient(String name, String surname, String pesel) {
this.name = name;
this.surname = surname;
this.pesel = pesel;
}
public String getName(){return name;}
public void setName(String name){this.name = name;}
public String getSurname(){return surname;}
public void setSurname(String surname){this.surname = surname;}
public String getPesel(){return pesel;}
public void setPesel(String pesel){this.pesel = pesel;}
}
My patientList:
(This method works, when i am using it to convert medicine json to medicine list i have no problem)
public List<Patient> FromJsonToArray1() throws IOException {
String patientsJson = initArray("Patients.json").toString();
Gson gson = new Gson();
java.lang.reflect.Type patientsListType = new TypeToken<ArrayList<Patient>>() {}.getType();
List<Patient> patientArray = gson.fromJson(patientsJson, patientsListType);
return patientArray;
}
And this is my function to show name of mine patient.
public void jtreecreator() throws IOException {
List<Medicine> medicineList = FromJsonToArray();
List<Patient> patientList = FromJsonToArray1();
medicinesDataMethods medicinesdatamethods = new medicinesDataMethods();
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Patients");
Patient c = patientList.get(0);
Medicine d = medicineList.get(0);
DefaultTreeModel treeModel = new DefaultTreeModel(root);
JTree tree = new JTree(treeModel);
JScrollPane scrollPane = new JScrollPane(tree);
JOptionPane.showMessageDialog(null,c.getSurname());
JOptionPane.showMessageDialog(null, d.getName());
}
And after call this function it display d.getName(), but c.getSurname() didnt work.
Its my json where i store my patients:
[
{
"Pesel": "1111",
"Surname": "Walker",
"Name": "Johny "
},
{
"Pesel": "11111",
"Surname": "Walker1",
"Name": "Johny1 "
}
]
After debug, i find out that my list which is created in FromJsonToArray1() has objects of patients but values of name, surname and pesel are null. :C
Issue is attribute names in class and json do not match. You can modify Patient class like
class Patient {
#SerializedName("Name")
private String name;
#SerializedName("Surname")
private String surname;
#SerializedName("Pesel")
private String pesel;
// getters and setters, constructor, etc. here
}

OpenCSV memberFieldsToBindTo not working - Java

I am trying to use OpenCSV to parse a CSV file into a list of objects so I can load student data into my Student Team Allocator system.
I have been following this guide under the heading 'Parsing the records into a Java Object'
After some issues with dependencies I have it outputting a list of Student objects, however the CSV columns are not bound to the member fields as they should be. Print test returns null values for every object's fields.
I have two constructors in Student, one that initialises the 3 fields, and one that is empty. I know currently the empty one gets used as removing this one causes InstantiationExceptions in the Student object.
CSVParser Class
public class CSVParser {
private static String CSV_FILE_PATH;
public CSVParser(String CSVPath){
CSV_FILE_PATH = CSVPath;
try (
Reader reader = Files.newBufferedReader(Paths.get(CSV_FILE_PATH));
) {
ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
strategy.setType(Student.class);
String[] memberFieldsToBindTo = {"fName", "sName", "stuNumber"};
strategy.setColumnMapping(memberFieldsToBindTo);
CsvToBean csvToBean = new CsvToBeanBuilder(reader)
.withMappingStrategy(strategy)
.withSkipLines(1)
.withIgnoreLeadingWhiteSpace(true)
.build();
List<Student> Students = csvToBean.parse();
for (Student s : Students) {
System.out.println("First Name : " + s.getFirstName());
System.out.println("Second Name : " + s.getSecondName());
System.out.println("StudentNo : " + s.getStudentNumber());
System.out.println("---------------------------");
}
} catch (IOException ex) {
Logger.getLogger(CSVParser.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Student Class
public class Student {
private String fName;
private String sName;
private String stuNumber;
private String skill;
private final String[] skills = {"Planning","Writing","Developing"};
public Student(){
}
public Student(String fName, String sName, String stuNumber) {
this.fName = fName;
this.sName = sName;
this.stuNumber = stuNumber;
}
// Setters
public void setSkill(int skillIndex){
this.skill = skills[skillIndex];
}
public void setFirstName(String fName){
this.fName = fName;
}
public void setSecondName(String sName){
this.sName = sName;
}
public void setStudentNumber(String stuNumber){
this.stuNumber = stuNumber;
}
// Getters
public String getFirstName(){
return fName;
}
public String getSecondName(){
return sName;
}
public String getStudentNumber(){
return stuNumber;
}
// Save to Database
private void saveStudent(){
// DBConnect db = new DBConnect();
}
}
The exception caused by non empty constructor
The print test showing null values in Student fields
Please let me know how I can make things any clearer,
Thanks.
The names in the column mapping array should respond to the names of the setters rather than the fields themselves. If it can't find a setter that correspond to the name, it can't set the value.

Cant access object properties java

List<Employeee> employees = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
String[] input = new String[6];
int n = Integer.valueOf(scanner.nextLine());
for (int i = 0; i < n; i++) {
input = scanner.nextLine().split(" ");
employees.add(new Employeee(input[0], Double.parseDouble(input[1]), input[2], input[3], input[4],
Integer.valueOf(input[5])));
}
for (Object i : employees) {
System.out.println(i.sallary); //And here ofc idk what to do to print them
System.out.println(i.name);
}
So here i just make a couple of object from my custom class and i put them inside of the list.
And after that i iterate over that list with a for loop and there i want to print their properties, but it doesn't let me. My Employeee class is simple I wont even paste the getters and setters from it.
public class Employeee {
private String name;
private double sallary;
private String possition;
private String department;
private String email;
private int age;
public Employeee(String name, double sallary, String possition, String department, String email, int age) {
this.name = name;
this.sallary = sallary;
this.possition = possition;
this.department = department;
this.email = email;
this.age = age;
}
}
There are numerous problems here.
You are mis-spelling your attribute names with wild abandon.
You are using Object in the for-each statement where you should be using Employee.
The fields you are trying to access directly from outside the class are declared as private, which means you can't. You should be using the respective accessor functions instead.

Arraylist java program

Help in writing a program using the array list which stores the values of name, address, phone number, date and time (for each customer) and later I need to retrieve the specific information like all the customer's name on a specified date. any help is appreciated.
Code:
public class Details {
public static void main(String args[]) throws IOException {
InputStreamReader rdr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(rdr);
String s;
s = br.readLine();
System.out.println("PLEASE ENTER CLIENT NAME");
String name = br.readLine();
System.out.println("PLEASE ENTER CLIENT ADDRESS");
String add = br.readLine();
System.out.println("PLEASE ENTER CLIENT CONTACT PHONE NUMBER");
String pnum = br.readLine();
List list = new ArrayList();
list.add("name");
list.add("add");
list.add("pnum");
list.add("food");
}
}
Create a class Customer like this -
public class Customer{
private String name;
private String address;
private String phoneNumber;
private Date date;
public Customer(name, address, phoneNumber, date){
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.date = date;
}
//getters and setters method
}
After that you create an ArrayList of Customer like this -
List<Customer> `customerList` = new ArrayList<Customer>();
Now create an object/instance of Customer like this -
Customer aCustomer = new Customer("ranjit", "someAddress", "023-859 74", new Date() );
Then add the Customer object/instance aCustomer to ArrayList of Customer - customerList like this:
customerList.add(aCustomer);
In the given way you can more easily handle a Customer. Now you have a single entity containing all the customer attributes (name, address, phoneNumber etc). So you don't need store all the attributes/property in separate ArrayList

Categories

Resources