Reading contents of a file into class objects - java

I have a text file of employee entries as follows:
000, first name1, middle name1
001, first name2, middle name2
002, first name3, middle name3
003, first name4, middle name4
004, first name5, middle name5
And I have a class Employee as follows:
public class Employee {
public int id;
public String fName;
public String mName;
public String lName;
}
I've read the contents of the file into an array. But what I want is to construct an array of objects of class Employee, and a way for each attribute of the class to be initialised with each entry. Something like this:
Employee e[] = new Employee[5];
Checking the details of each object in the array...
e[0].id = 000
e[0].fName = "first name1"
e[0].mName = "middle name1"
e[0].lName = "last name1"
Then,
e[1].id = 001
And so on...
Is there any way I can do this?

public class Employee {
public int id;
public String fName;
public String mName;
public String lName;
public Employee(String line) {
String[] split = line.split(",");
id = Integer.parseInt(split[0]);
fName = split[1];
mName = split[2];
lName = split[3];
}
}
Since you already read the file into array (of string I suppose).
String[] lines = ....;
Employee[] employees = new Employee[lines.length];
for(int i = 0; i < lines.length; i++) {
employees[i] = new Employee(lines[i]);
}
There you go... you have an array of employees.

Read the file and loop over its content line by line. Then parse the lines and create a new Employee() in each iteration. Set your values, such as id and name. Finally, add your new Employee instance to a List<Employee> and continue with the next entry.
// Read data from file
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
// List to collect Employee objects
List<Employee> employees = new ArrayList<Employee>();
// Read file line by line
String line = "";
while ((line = br.readLine()) != null) {
// Parse line to extract individual fields
String[] data = this.parseLine(line);
// Create new Employee object
Employee employee = new Employee();
employee.id = Integer.valueOf(data[0]);
employee.fName = data[1];
employee.mName = data[2];
// Add object to list
employees.add(employee);
}
// Further process your Employee objects...
}
Also, there are CSV libraries that can handle all the nasty parts of reading a file that has comma separated values. I'd suggest using OpenCSV, for example.

Here already answers posted but I still gonna post mine...
package com.stackoverflow.java.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Employee {
public int id;
public String fName;
public String mName;
public Employee(int id, String fName, String mName) {
this.id = id;
this.fName = fName;
this.mName = mName;
}
public static void main(String[] args) throws IOException {
Employee[] e = new Employee[5];
FileReader fr=new FileReader("YourDoc.txt");
BufferedReader br=new BufferedReader(fr);
String line="";
String[] arrs=null;
int num=0;
while ((line=br.readLine())!=null) {
arrs=line.split(",");
e[num] = new Employee(Integer.valueOf(arrs[0]), arrs[1], arrs[2]);
num++;
}
br.close();
fr.close();
for(int i=0 ; i< e.length; i++) {
System.out.println(e[i].id + " and " + e[i].fName + " and " + e[i].mName);
}
}
}

try :
public static void main(String[] args) throws IOException {
File f1 = new File("d:\\data.txt");
Scanner scanner = new Scanner(f1);
List<Employee1> empList=new ArrayList<>();
while(scanner.hasNextLine()){
String data[]=scanner.nextLine().split(",");
empList.add(new Employee(Integer.parseInt(data[0]),data[1],data[2],data[3]));
}
scanner.close();
System.out.println(empList);
}
Employee.java
class Employee{
public int id;
public String fName;
public String mName;
public String lName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public Employee(int id, String fName, String mName, String lName) {
super();
this.id = id;
this.fName = fName;
this.mName = mName;
this.lName = lName;
}
#Override
public String toString() {
return "Employee [id=" + id + ", fName=" + fName + ", mName="
+ mName + ", lName=" + lName + "]";
}
}

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
}
}
}
}

generating groups from txt file and generating them based on preferences

I am designing a group generator that takes in preferences such as “mix gender”, “mix nationality”... I am putting a list of student names, followed by nationality and gene set, in an arraylist. What is the easiest way to generate groups, based on user input, that each group consists of people from different nationalities, or balanced gender.
public ArrayList<String> readEachWord(String className)
{
ArrayList<String> readword = new ArrayList<String>();
Scanner sc2 = null;
try {
sc2 = new Scanner(new File(className + ".txt"));
} catch (FileNotFoundException e) {
System.out.println("error, didnt find file");
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.next();
readword.add(s);
}
}
return readword;
}
I am using this to read a text file, and on each line, I have each student's name nationality and gender. I put them into an ArrayList and am right now trying to figure out how to evenly distribute them based on the user-desired group numbers.
I am using a txt file to store all the information since this group generator is customized for my school.
You can use the groupinBy method
basic tutorial
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class Scratch {
public static void main(String[] args) {
String student1 = "Macie American Female";
String student2 = "Yago Brazilian Male";
String student3 = "Tom American Male";
List<String> students = Arrays.asList(student1, student2, student3);
System.out.println(groupByGender(students));
System.out.println(groupByNationality(students));
}
private static Map<String, List<Student>> groupByNationality(List<String> students) {
return students.stream().map(s -> mapToStudent(s)).collect(Collectors.groupingBy(Student::getNationality));
}
private static Map<String, List<Student>> groupByGender(List<String> students) {
return students.stream().map(s -> mapToStudent(s)).collect(Collectors.groupingBy(Student::getGender));
}
private static Student mapToStudent(String s) {
String[] ss = s.split(" ");
Student student = new Student();
student.setName(ss[0]);
student.setNationality(ss[1]);
student.setGender(ss[2]);
return student;
}
private static class Student {
String name;
String nationality;
String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", nationality='" + nationality + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
}
First of all, it would be better if you put your while loop inside the try block because you don't want to get there if the file hasn't been found.
Second, you don't need to create a new instance of Scanner just to read every line. You can simply read your file word by word:
while (sc2.hasNext())
readword.add(sc2.next());
To group the students according to their nationality, you can do something like that:
String nationality = [UserInput] ;
List<String> group = new ArrayList<>();
for (int i = 0; i < readword.size(); i++)
if (readword.get(i + 1).equals(nationality)
group.add(readword.get(i));

Loading and editing a CSV file in Java into a List

I'm working on a private project where i need to load a CSV file, keep it in the program and edit if needed.
The file looks like this:
ID;Name;Last Login;RevState;List
157;Guy;"01.11.19";false;"tag, cup, sting"
A60;Dud;"07.10.19";true;"ice, wood, cup, tag"
1D5;Wilfred;"11.11.19";true;"beer, food, cup, shower"
I will only ever have a single csv file loaded. I need to be able to edit every single data point. I need to be able to retrieve all the information of one "category", e.g. get all names.
So what I plan to do is load the CSV via
Scanner scanner = new Scanner(new File(file.csv))
Create a class that holds the information of a line
public class User
private String id;
private String name;
private String lastLogin;
private String list;
public getter and setter methods
Create a list
private List<User> csvList = new List<User>();
And then store every line as
while (file.hasNextLine())
[...] parse the line
User user = new User(id, name, lastLogin, list);
csvList.add(user);
Would this work, or is there a better method that I can't think of right now?
Here it goes:
public class User {
private int id;
private String name;
private String email;
private String phone;
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
Main class
import java.io.*;
import java.util.*;
public class Main {
public static void main(String [] args ) throws Exception {
List<User> users = new ArrayList<>();
String path = System.getProperty("user.dir");
FileInputStream fileInputStream = new FileInputStream(path+"/src/"+"users.csv");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
String line = "";
int lines = 0;
while((line=bufferedReader.readLine())!=null){
lines++;
String [] columns = line.split(",");
if(lines ==1 ) {
continue;
}
else {
User user = new User();
user.setId(Integer.parseInt(columns[0]));
user.setName(columns[1]);
user.setEmail(columns[2]);
user.setPhone(columns[3]);
users.add(user);
}
}
for(int i=0;i< users.size();i++){
System.out.println(users.get(i));
}
}
}
And users.csv file
Id, Name, Email, Phone
1, John, john.doe#gmail.com, 123456789

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.

Dynamically fill in an ArrayList with objects

I have the abstract class Human, which is extendet by other two classes Student and Worker. I`m am trying to fill in two array lists. ArrayList of type Student and ArrayList of type Worker dynamically.
public abstract class Human {
private String fName = null;
private String lName = null;
public String getfName() {
return fName;
}
public Human(String fName, String lName) {
super();
this.fName = fName;
this.lName = lName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
}
public class Student extends Human {
private String grade = null;
public Student(String fName, String lName, String grade) {
super(fName, lName);
this.grade = grade;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
public class Worker extends Human {
private int weekSalary = 0;
private int workHoursPerDay = 0;
public Worker(String fName, String lName, int weekSalary, int workHoursPerDay) {
super(fName, lName);
this.weekSalary = weekSalary;
this.workHoursPerDay = workHoursPerDay;
}
public int getWorkSalary() {
return weekSalary;
}
public void setWorkSalary(int workSalary) {
this.weekSalary = workSalary;
}
public int getWorkHoursPerDay() {
return workHoursPerDay;
}
public void setWorkHoursPerDay(int workHoursPerDay) {
this.workHoursPerDay = workHoursPerDay;
}
public int moneyPerHour() {
return weekSalary / (5 * workHoursPerDay);
}
}
public class Program {
public static void main(String[] args) {
ArrayList<Student> student = new ArrayList<>();
ArrayList<Worker> worker = new ArrayList<>();
}
}
Sure, just add the students:
ArrayList<Student> students = new ArrayList<>(); // note: students
students.add(new Student("Jens", "Nenov", "A+"));
You can do almost exactly the same thing for the workers. If you want to use a loop, do the following:
for (int i=0; i<50; i++) {
students.add(new Student("Jens"+i, "Nenov", "A+"));
}
This will create a list of new students with different numbers after their names. If you want different data, though, that data needs to come from somewhere. For example, you might get the data from user input:
Scanner input = new Scanner(System.in);
for ...
System.out.println("Enter a first name:");
String firstname = input.nextLine();
...
students.add(new Student(firstname, lastname, grade));

Categories

Resources