OpenCSV memberFieldsToBindTo not working - Java - 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.

Related

How can we create an instance for a nested class in array of objects in java?

import java.util.Arrays;
import java.util.Scanner;
public class employee{
public String name;
public class employee_address{
String street_name;
String city;
String zipcode;
String state;
String country;
}
public static void main(String []args){
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt();
employee[] employees_list = new employee[no_of_employees];
for(int i = 0;i < no_of_employees;i++){
employees_list[i].name = user_input.nextLine();
employees_list[I].employee_address = // this is it ?
}
}
}
In the code above I do understand that the employee_address is a class and can't be accessed
directly without an instance being created like in the code, that makes no sense. but how can I create an instance of the employee_address class that is associate with each employee.
like in the code above 'employee_address' is associated with every employee but how can the class 'employee_address' be initialised and how can I set the street_name, city and the rest of the members in the address class. any ideas would be appreciated.
You can't directly create an instance of inner class, the reason because since it is the property of another instance we always need to use it though the instance of parent variable.
Let's say you have a class, which have two propeties:
public class Employee {
public String name;
public EmployeeAddress emAddress;
}
to access emAddress you need to use through the instance of Employee class, for example -
Employee object = new Employee();
EmployeeAddress empAdd = object.new EmployeeAddress();
Full code:
public class Employee {
public String name;
public EmployeeAddress emAddress;
public class EmployeeAddress {
String street_name;
String city;
String zipcode;
String state;
String country;
public String getStreet_name() {
return street_name;
}
public void setStreet_name(String street_name) {
this.street_name = street_name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString() {
return "EmployeeAddress [street_name=" + street_name + ", city=" + city + ", zipcode=" + zipcode
+ ", state=" + state + ", country=" + country + "]";
}
}
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt(); // let's say no_of_employees = 1
Employee[] employees = new Employee[no_of_employees];
for (int i = 0; i < no_of_employees; i++) {
Employee object = new Employee();
object.setName("Virat Kohli");
EmployeeAddress empAdd = object.new EmployeeAddress();
empAdd.setCity("New Delhi");
empAdd.setCountry("India");
empAdd.setState("Delhi");
empAdd.setStreet_name("Chandni Chalk");
empAdd.setZipcode("741124");
object.setEmAddress(emAddress);
employees[i] = object;
}
System.out.println(employees[0]);
user_input.close();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public EmployeeAddress getEmAddress() {
return emAddress;
}
#Override
public String toString() {
return "Employee [name=" + name + ", emAddress=" + emAddress + "]";
}
public void setEmAddress(EmployeeAddress emAddress) {
this.emAddress = emAddress;
}
}
I have modified your code to sonar standard.
Below code uses Java naming conventions (which your code does not).
Notes after the code.
import java.util.Scanner;
public class Employee {
private String name;
private EmployeeAddress address;
public class EmployeeAddress {
String streetName;
String city;
String zipcode;
String state;
String country;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int noOfEmployees = userInput.nextInt();
Employee[] employeesList = new Employee[noOfEmployees];
for (int i = 0; i < noOfEmployees; i++) {
employeesList[i] = new Employee();
employeesList[i].name = userInput.nextLine();
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
employeesList[i].address = employeeAddress;
employeesList[i].address.streetName = userInput.nextLine();
}
}
}
An inner class is a normal class. It is not a member of its enclosing class. If you want class Employee to have an [employee] address, as well as a [employee] name, you need to add another member variable to class Employee whose type is EmployeeAdress.
Employee[] employeesList = new Employee[noOfEmployees];
The above line creates an array but every element in the array is null. Hence you need to first create a Employee object and assign it to an element of the array. Hence the following line in my code, above:
employeesList[i] = new Employee();
Since EmployeeAddress is not a static class, in order to create a new instance, you first need an instance of the enclosing class, i.e. Employee. Hence the following line in the above code.
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
Since all your code is in class Employee, in method main you can directly access the members of both class Employee and EmployeeAddress. Nonetheless you need to be aware of the different access modifiers in java.
A few hints:
stick to naming conventions: class names in Java start with capital letters
use (class) definitions before using them (collect them at the top if not inconventient)
if you are sure you want to use inner classes, set them static, unless you want them to be entangled in generics.
Usually normal classes in each their own file are a lot more flexible and far easier to use
if you use objects that only carry public data, try to use final keyword and initialize them ASAP
use proper objects first, and after finishing them assign them to arrays. avan better would be the use of ArrayList and the like
if Employee contains EmployeeAddress, it should initialize it if conventient. so an object is always responsible for its own stuff
Use try/resrouce/catch
scanner.nextInt() can be problematic with newline/line breaks. For user input better readLine() and parse input
Code:
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
static public class EmployeeAddress {
public final String street_name;
public final String city;
public final String zipcode;
public final String state;
public final String country;
public EmployeeAddress(final Scanner pScanner, final PrintStream pOutPS) {
street_name = readLine(pScanner, pOutPS, "Please enter Street Name:");
city = readLine(pScanner, pOutPS, "Please enter City Name:");
zipcode = readLine(pScanner, pOutPS, "Please enter Zip Code:");
state = readLine(pScanner, pOutPS, "Please enter State:");
country = readLine(pScanner, pOutPS, "Please enter Country:");
}
}
static public String readLine(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
pOutPS.print(pPrompt);
final String value = pScanner.nextLine();
pOutPS.println();
return value;
}
static public int readInt(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
return Integer.parseInt(readLine(pScanner, pOutPS, pPrompt));
}
public final String name;
public final EmployeeAddress address;
public Employee(final Scanner pScanner, final PrintStream pOutPS) {
name = readLine(pScanner, pOutPS, "Please enter Employee Name: ");
System.out.println("Name: " + name);
address = new EmployeeAddress(pScanner, pOutPS);
}
public static void main(final String[] args) {
try (final Scanner user_input = new Scanner(System.in);
final PrintStream output = System.out;) {
final int no_of_employees = readInt(user_input, output, "Please enter number of users: ");
final Employee[] employees_list = new Employee[no_of_employees]; // either this line
final ArrayList<Employee> employees = new ArrayList<>(); // or this line
for (int i = 0; i < no_of_employees; i++) {
output.println("Creating user #" + (i + 1) + "...");
final Employee newEmployeeWithAddress = new Employee(user_input, output);
employees_list[i] = newEmployeeWithAddress; // either this line
employees.add(newEmployeeWithAddress); // or this line
}
}
}
}

Simple program for making shifts

My dad asked me to make a program for him that will randomly take a name, surname etc. from Excel (or CSV file) and assign employees to the work. Each person must be at work minimum once and maximum 4 times a month. Program output should look like this:
Day 1: John Smith, James Smith Day 2: Charlie Smith, Thomas Smith
And this is how my code looks like right now
public static void main(String[] args) {
String FileName = "excel.csv";
File f = new File(FileName);
String read = "";
Map<Integer, Surname>SurnameArray = new HashMap<Integer, Surname>();
try {
Scanner scanner = new Scanner(f);
while(scanner.hasNextLine()) {
read = scanner.nextLine();
String[] arraySplit = read.split(",");
int kod = Integer.parseInt(tablicaSplit[0]);
String rank = tablicaSplit[1];
String name = tablicaSplit[2];
String surname = tablicaSplit[3];
SurnameArray.put(kod, new Nazwiska(kod, rank, name, surname));
SurnameArray.get(kod).getAll();
}
} catch (FileNotFoundException e) {
System.out.println("No file!");
}
}
}
And the second class looks like this:
Class Surnames {
private int kod;
private String rank;
private String name;
private String surname;
public Surnames(int kod, String rank, String name, String surname) {
super();
this.kod = kod;
this.rank = rank;
this.name = name;
this.surname = surname;
}
public void getAll() {
System.out.println(rank + " " + name + " " + surname);
}
public int getKod() {
return kod;
}
public void setKod(int kod) {
this.kod = kod;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setNazwisko(String surname) {
this.surname = surname;
}
}
I'm stuck at this moment. I think that this code is more complicated than it should be. If someone could show me how can i make it or maybe there is simpler way to make something like this.
I would do it this way:
class Surnames{
private final HashSet<String> EMPLOYEES;
private ArrayList<String> positions;
Surnames(String csv){
HashSet<String> tempEMPLOYEES = new HashSet<>();
ArrayList<String> tempPositions = new ArrayList<>();
/*here the code for putting csv data ino an tempEMPLOYEE hashSet, or a static setter method doing this, as well for tempPositions, containing array list of positions remember to check
if the hashset's size is equal or lower than arrayList's*/
EMPLOYEES = tempEMPLOYEES;
positions = tempPosition;
}
public void printShift(){
for(int i = 0; i < EMPLOYEES.size(); i++){
System.out.println(positions.get(i) + "- " + EMPLOYEES.get(i));
}
}
}
Since hashSet gives different object position in the set every single run of the program, placing EMPLOYEES to positions will be random. I mentioned checking that HashSet EMPLOYEES should be less size than positions. I iterate on the hashset- every employee should get a position.

Java - Reading in a CSV file into a constructor

Java (Constructor issue)
Trying to figure out how to read in a CSV file into a constructor. Theme is harry potter and I'm reading in 4 files (Gryffindor, Hufflepuff, Ravenclaw, Slytherin). Reading this into my House.java, but School.java and Student.java have constructors/getters and setters as well. Supplied below. For instance a within a School exists a House and within that exists a Student. In the 4 CSV files provided, each file is a name of a "House" in which you would read in the file as "Students" (first name, last name, year).
These 3 java files are within application.model to support an application in JavaFX using the MVC format. It's specifically tailored in this fashion for the sake of grading.
House.java
public class House {
private String name;
private String color;
private String professor;
public ArrayList<Student> Students;
public House(String name, String color, String professor, ArrayList stdList) {
this.name = name;
this.color = color;
this.professor = professor;
this.Students = stdList;
}
public ArrayList<Student> sortStudents(ArrayList<Student> allStudents) {
if (allStudents != null) {
Collections.sort(allStudents, new SortTool());
}
return allStudents;
}
public void dataLoader() {
String fileName = "Gryffindor.csv";
String content = null;
/*
* Shows working path System.out.println(newFile(".").getAbsoluteFile());
*/
try {
Scanner inputStream = new Scanner(new File(fileName));
// Delimits by commas and (enter or \n)
inputStream.useDelimiter("[,\n]");
// Iteration rather than iterable
while (inputStream.hasNext()) {
content = inputStream.nextLine();
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
School.java
public class School {
private String name;
private int enrollment;
private House houses[];
/*
* School Constructor
*
* #param pass in name to set name
*/
public School(String name) {
this.name = name;
houses = new House[4];
enrollment = 0;
}
}
Student.java
public class Student {
private String firstName;
private String lastName;
private int year;
public Student(String firstName, String lastName, int year) {
this.firstName = firstName;
this.lastName = lastName;
this.year = year;
}
}
SortTool.java
public class SortTool implements Comparator {
#Override
public int compare(Student a, Student b) {
int c = a.getYear() - b.getYear();
if (c == 0)
c = a.getLastName().compareTo(b.getLastName());
if (c == 0)
c = a.getFirstName().compareTo(b.getFirstName());
return c;
}
}
Trying to be discrete about the entire program since I wrote it and don't want it to be tracked as plagerism.
House.java - how do I read into this CSV file into a constructor. Comma delmited and needs to be read in and not manually entered.
Example of Gryffindor.csv
Colin Creevy,1, Hermione Granger,2, Harry Potter 2,
Well you can read the file the constructor of the House class. Just add a private method that will populate the Students arrayList.
You have to open the file giving the path of where each houses files are located and append it with "/"+this.name+".csv", and then for each line of the file you read, you parse it and add a new Student in the arraylist.
Example of the method :
private void populateHouseFromFile(){
String line;
br = new BufferedReader(new FileReader(PATH_TO_HOUSES+"/"+this.name+".csv"));
while ((line = br.readLine()) != null) {
String[] split = line.split(",",3); //Retrieve each part of the student information , assuming each field is separated with a "," and each line is new entry.
this.Students.add(new Student(split[0],split[1],Integer.decoded(split[2])));
}
}
You should check that int the constructor of student that the argument passed are not stupid (negative year, etc if bad constructed .csv).

Convert a ResultSet into List of HashMap in java

I have a resultset (returned by a stored procedure) like -
I need a List of HashMap, and HashMap will be made of individual (distinct by combination of FirstName, LastName and Id) students records. Below image will describe the structure of HashMap.
So, basically in this example, I need a list of 3 HashMap.
Can you please suggest some efficient way to do that? Thanks!
why do I need a list of hashmap for this?
I need to create an XML file out of this ResultSet. List of HashMap is the best way I can think of for required XML structure.
XML Structure :
If my approach is not correct in terms of coding standard or efficiency, please suggest me different approach.
What I am thinking:
I've not tried yet. But can not think anything else other than iterating over the ResultSet and temporarily storing FirstName, LastName and Id to check if it is same as previous value or not. If same then add marks array to MarksList, else consider it as record of another student. I am hoping there might be a different way.
[Update]:
I think I should use list of Objects, not list of HashMap. But the question still is, how can I interpret the value from resultset and set values into the object.
UPDATE
Provided code to extract the data from the ResultSet correctly into the objects used by JAXB.
You don't need a HashMap and/or a List of HashMap to create a xml file
You can do this easily with JAXB, provided you create the correct data objects.
First, create classes to match the structure desired to be in the xml.
a ScoreRecord class which holds the course information such as course name and mark.
a Student class which holds student info such as firstname, lastname and a list of ScoreRecords objects.
a StudentGroup class which holds all the students belonging to the same faculty group
The ScoreRecord class:
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "Mark")
#XmlType(propOrder = { "sub", "percent" })
public class ScoreRecord {
private String sub;
private String percent;
public void setSub(String sub) {
this.sub = sub;
}
public String getSub() {
return sub;
}
public void setPercent(String percent) {
this.percent = percent;
}
public String getPercent() {
return percent;
}
}
The Student class:
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "Student")
#XmlType(propOrder = { "firstName", "lastName", "id", "scoreRecords" })
public class Student {
private Integer id;
private String firstName;
private String lastName;
private List<ScoreRecord> scoreRecords;
public void setId(Integer id) {
this.id = id;
}
#XmlElement(name = "Id")
public Integer getId() {
return id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#XmlElement(name = "FirstName")
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#XmlElement(name = "LastName")
public String getLastName() {
return lastName;
}
public void setScoreRecords(List<ScoreRecord> scoreRecords) {
this.scoreRecords = scoreRecords;
}
#XmlElementWrapper(name = "MarksList")
#XmlElement(name = "Mark")
public List<ScoreRecord> getScoreRecords() {
return scoreRecords;
}
}
The StudentGroup class:
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "Records")
public class StudentGroup {
private List<Student> students;
public void setStudents(List<Student> students) {
this.students = students;
}
#XmlElement(name = "StudentRecord")
public List<Student> getStudents() {
return students;
}
}
Now, create a class to hold the data "as is" from the database
public class DbStudent {
private String firstName;
private String lastName;
private Integer id;
private String sub;
private String percent;
public DbStudent(String firstName, String lastName, int id, String sub, String percent) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.sub = sub;
this.percent = percent;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setSub(String sub) {
this.sub = sub;
}
public String getSub() {
return sub;
}
public void setPercent(String percent) {
this.percent = percent;
}
public String getPercent() {
return percent;
}
}
Create a method to retrive the data as a List of this object type. I assume you already have something that gets the ResultSet, iterate it and .add to the list of DbStudent objects.
Something like:
public List<DbStudent> getStudents() throws ClassNotFoundException, SQLException {
List<DbStudent> entries = new ArrayList<DbStudent>();
Class.forName(databaseDriver);
this.connection = DriverManager.getConnection(connectionString);
Statement sttm = this.connection.createStatement();
ResultSet rs = sttm.executeQuery("select * from TMP_STUDENT"); //in your case procedure call
if (rs != null) {
while (rs.next()) { //add the results into the list
entries.add(new DbStudent(rs.getString("FIRSTNAME"), rs.getString("LASTNAME"), rs.getInt("ID"),
rs.getString("SUB"), rs.getString("PERCENT")));
}
rs.close();
}
return entries;
}
Now, the main method. It contains logic to extract all the info from the list of database objects. Basically we sort it by id, iterate through it checking if we find or not a new student. If we find a new student, we add the previous one to a list of Student objects. This student already has his marks set.
public static void main(String[] args) throws JAXBException {
//get the data from the database as is
OracleConnection myOracleConnection = new OracleConnection(ORACLE_DRIVER, ORACLE_CONN);
List<DbStudent> dbStudentList = null;
try {
dbStudentList = myOracleConnection.getStudents(); //get the list of students from the procedure or query
myOracleConnection.CloseConnection();
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("Stopping execution and exiting...");
System.exit(-1);
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Stopping execution and exiting...");
System.exit(-1);
}
//sort the list on Id, so we can know when we find a new student
Collections.sort(dbStudentList, new Comparator<DbStudent>() {
public int compare(DbStudent s1, DbStudent s2) {
return s1.getId().compareTo(s2.getId());
}
});
List<Student> studentList=new ArrayList<Student>(); //list which will hold all the student objects
Integer previousId = 0; //control variable
List<ScoreRecord> marksList = new ArrayList<ScoreRecord>(); //list to store the marks for each student
Student s = null;
for (int i=0;i<dbStudentList.size();i++) {
if(i==dbStudentList.size()-1){ //if we reached the end, no more students after this record, set the marks and add the student to the list
s.setScoreRecords(marksList);
studentList.add(s);
}
if (dbStudentList.get(i).getId().compareTo(previousId) != 0) {
//new student found
if(s!=null){
//if new student found add the previous one to the list after setting the marks
s.setScoreRecords(marksList);
studentList.add(s);
}
s = new Student(); //create a new student
s.setFirstName(dbStudentList.get(i).getFirstName());
s.setId(dbStudentList.get(i).getId());
s.setLastName(dbStudentList.get(i).getLastName());
ScoreRecord sr = new ScoreRecord();
sr.setSub(dbStudentList.get(i).getSub());
sr.setPercent(dbStudentList.get(i).getPercent());
marksList = new ArrayList<ScoreRecord>(); //reset marks list
marksList.add(sr);
} else {
//same student
ScoreRecord sr = new ScoreRecord();
sr.setSub(dbStudentList.get(i).getSub());
sr.setPercent(dbStudentList.get(i).getPercent());
marksList.add(sr); //add mark to existing marks list
}
previousId=dbStudentList.get(i).getId(); //set the control variable to the new id
}
StudentGroup sg=new StudentGroup(); //create the student wrapper
sg.setStudents(studentList); //add the student list to the wrapper
//create xml with JAXB
JAXBContext context = JAXBContext.newInstance(StudentGroup.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(sg, new File(STUDENT_XML));
}
The output of the xml is exactly how you want it:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Records>
<StudentRecord>
<FirstName>AA1</FirstName>
<LastName>BB1</LastName>
<Id>1</Id>
<MarksList>
<Mark>
<sub>Math</sub>
<percent>51%</percent>
</Mark>
<Mark>
<sub>Phy</sub>
<percent>61%</percent>
</Mark>
<Mark>
<sub>Bio</sub>
<percent>61%</percent>
</Mark>
</MarksList>
</StudentRecord>
<StudentRecord>
<FirstName>AA2</FirstName>
<LastName>BB2</LastName>
<Id>2</Id>
<MarksList>
<Mark>
<sub>Bio</sub>
<percent>62%</percent>
</Mark>
</MarksList>
</StudentRecord>
<StudentRecord>
<FirstName>AA3</FirstName>
<LastName>BB3</LastName>
<Id>3</Id>
<MarksList>
<Mark>
<sub>Math</sub>
<percent>53%</percent>
</Mark>
<Mark>
<sub>Phy</sub>
<percent>63%</percent>
</Mark>
<Mark>
<sub>Chem</sub>
<percent>63%</percent>
</Mark>
</MarksList>
</StudentRecord>
</Records>
What you need here is correct Data object. Here it should Student record which internally should hold the list of score records
which will have id,FirstName , LastName, scoreRecords(it should be list holding subject name, marks, % etc).
Then simply convert it into XML with JAXB
If you sort your sql-statement/storedprocedure by LastName and FirstName you don't need to collect the whole data in memory.
Simply iterate your resultset and collect the data until FirstName and LastName changes, than aggregate your sub and percent data and stream it directly to a file or a dom. And so on....
Or change the stored procedure or create a new one in that way that it already aggregates the data for you.

Setting Variable in Class that Extends other class

the psuedo for what im trying to do is
-send Array of EMPLOYEE objects to Restaurant Class
-In Class RESTAURANT give each of the employee objects a name and last name (last name not in employee Class but in PERSON Class which Employee CLass Extends.
-print say employeeList[1].getLastName()
hopefully my code explains better
class Person {
public Person(final String last) {
}
}
class Employee extends Person {
private String firstName;
// getFirstName method
// getLastName Method
Employee(final String first, final String last) {
super(last);
}
}
class Restaurant { // set first object in array have first and last name
public void setFirstLast(final Employee[] employeeList) {
String firstName = "Jovana";
String lastName = "Valdez";
employeeList[0] = new Employee(firstName, lastName); // set up via constructor
}
}
public class Main {
private String lastName;
public static void main(final String[] args) {
Employee[] employeeList = new Employee[1]; // my array of Employee objects, all set to null
Restaurant restaurant = new Restaurant();
restaurant.setFirstLast(employeeList);
}
}
from main when i try to print System.out.printf("first is %d\n",arrayList.getFirst()); i get null for the value as well as the value for the last name so what is the correct way to go about and set values to objects in the array?
Edit arrayList initialized in Class restaurant by
public Table[] create_table_array(Table table,int number) {
Table[] TableList = new Table[number];
int i = 0;
for(i = 0; i < number; i++) {
TableList[i] = table;
}
return TableList;
Your constructor doesn't save firstName, it should look like:
Employee(String first, String last) {
super(last);
firstName = first;
}
You did not make good constructor of Person class and it class does not have instance variable lastName in which you should assign value you get in constructor as a parameter.
Also constructor of Employee does not assign any value to firstName.
What ArrayList ?As i see you are working with arrays?I didn't see it in code anywhere?
System.out.printf("first is %d\n",**arrayList**.getFirst());so command is wrong.
Any code that has meaning to me and can be compilled is to fix those things and delete formatting options you putted in System.out.printf because you are not formatting numbers.
So code look like :
class Person {
String lastName;
public Person(final String last) {
lastName=last;
}
}
class Employee extends Person {
private String firstName;
public String getFirstName()
{return firstName;}
public String getLastName()
{return lastName;}
Employee(final String first, final String last) {
super(last);
firstName=first;
}
}
class Restaurant { // set first object in array have first and last name
public void setFirstLast(final Employee[] employeeList) {
String firstName = "Jovana";
String lastName = "Valdez";
employeeList[0] = new Employee(firstName, lastName); // set up via constructor
}
}
public class Main {
private String lastName;
public static void main(final String[] args) {
Employee[] employeeList = new Employee[1];
Restaurant restaurant = new Restaurant();
restaurant.setFirstLast(employeeList);
System.out.printf("first is "+employeeList[0].getFirstName()+" "+employeeList[0].getLastName());
}
}

Categories

Resources