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).
Related
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.
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.
I am stuck. I don't know how to read a data value from a file to class object. I have to do it for three references for the class Employee. This is what I have so far as of now:
public void displayEmployees(View view)
{
EditText edt1;
TextView tv;
String urlfile; //For variable that stores the user input for url address
edt1 = (EditText) findViewById(R.id.edit_file);
tv = (TextView) findViewById(R.id.text_main);
//Declare references to class Employee
Employee e1;
Employee e2;
Employee e3;
//Create three objects for class Employee
e1 = new Employee();
e2 = new Employee();
e3 = new Employee();
//Retrieve what user has input
urlfile = edt1.getText().toString();
//Open and read the data values from a file on the web
try
{
//Create URL object
URL file_url = new URL(urlfile);
//try to open the file from the web
Scanner fsc = new Scanner(file_url.openStream());
}
catch(IOException e)
{
tv.setText("Error: Invalid URL Address or File Does Not Exist");
}
}
And, this is what the class looks like:
public class Employee {
private String name;
private String id;
private double salary;
private String office;
private String extension;
private int yearsofservice;
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public String getId()
{
return id;
}
public void setId(String ID)
{
id = ID;
}
public double getSalary()
{
return salary;
}
public void setSalary(double Salary)
{
salary = Salary;
}
public String getOffice()
{
return office;
}
public void setOffice(String Office)
{
office = Office;
}
public String getExt()
{
return extension;
}
public void setExt(String Extension)
{
extension = Extension;
}
public int getYearsOfServ()
{
return yearsofservice;
}
public void setYearsOfServ(int YearsOfService)
{
yearsofservice = YearsOfService;
}
}// end class Employee
Lastly, the file that I am reading from look like this, for example:
Joe Bob
00001
9000.00
Campus Hall
9999
5
I would rather use SQlite to persist the employee information.
for your problem you need to write your own parsing logic.
for reading check this question
Follow these steps
1)Connect to data source.
2)In Source side make a Model class as getter and setter.
3)Create a Object of that class and Insert all Values using Setters.
4)And add that Object in the collections(List,Map,Set) if you are using(Make return object
5)On the Android app get that in same signature which is return type of Server side value setter.
6)In android site you can do something like suppose you are getting an ArrayList then
for(int i=0;i<yourArrayList.size();i++){
VarType var=yourArrayList.get(i).getFirstSetvalue();
VarType var2=yourArrayList.get(i).getSecondValue()
//do what you want
Hope this will help you
The goal of this project is to read a movie data base txt file, where each line in the file contains the name, year released, and associated actors for one movie. Each piece of information is separated by ‘/’ characters. The year is specified inside parentheses at the end of the movie name. I have already created an actor class, which stores a String firstname and a String lastname, and a movie class which holds all the above info about the movie. In the movieDataBase class, I need to load the .txt file, and split it in to the different components. I understand how to split the file in to different elements, I just don't know how to turn the string of associated actors into and arrayList of Actor objects. Sorry for the newbie question. My java book doesn't talk about it at all and I have been looking for the past 3 hours on the internet! Here's my code:
public class Actor {
private String firstName;
private String lastName;
public Actor(){
firstName = "";
lastName = "";
}
public Actor( String first){
this (first, "");
}
public Actor( String first, String last){
firstName = first;
lastName = last;
}
public String getFirstName(){
return firstName;
}
public void setFirstName( String first){
firstName = first;
}
public String getLastName(){
return lastName;
}
public void setLastName( String last){
lastName = last;
}
public String toString(){
return firstName + " " + lastName;
}
}
//new class
public class MovieDatabase
public void loadDataFromFile( String aFileName) throws FileNotFoundException{
//creating a scanner to read the file
Scanner theScanner = new Scanner(aFileName);
theScanner = new Scanner(new FileInputStream("cast-mpaa.txt"));
while(theScanner.hasNextLine()){
String line = theScanner.nextLine();
String[] splitting = line.split("/");
String movieTitle = splitting[0];
filmActors.add(splitting[2]);
//this is where I have issues
ArrayList<Actor> associatedActors = new ArrayList<Actor>();
for( String newActors : filmActors){
}
}
}
}
You could do something like:
for( String newActor : filmActors){
associatedActors.add(new Actor(newActor));
}
This means with new Actor you are creating a new object instance of Actor and adding it to the array List that you created.
To Actor class, you are passing the actor name in constructor and that's how you are constructing the Actor object i assume.
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());
}
}