reading a .csv file into an array in java - java

I have a class called EmpQuery that I am trying to create an array of objects for my Employee class to hold data that comes from a employeedatabase.csv file.
The database appears like what is shown below. I need to use a stream-processing-algorithm..
Loop till EOF{
read in 1 record
Deal with that record completly
}
EX.
Employee ID,Full Name,Department,Start Date,Earnings
EMP001,Adele M. Fulton,Engineering,10/28/2008,"$104,000.00"
EMP002,Ali T. Herman,Engineering,2/27/2012,"$337,522.00"
EMP003,Alika C. Crawford,Engineering,6/2/2009,"$144,000.00"
So far i just have this much set up
public class EmployeeDB {
private static String[] empID = new String[300];
private static String[] empName = new String[300];
private static String[] department = new String[300];
private static String[] startDate = new String[300];
private static String [] earnings = new String[300];
private static String [] empDataBase = new String[300];
/**
* #param args the command line arguments
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
fillDataArray();
}
public class employee{
String empID;
String empName;
String department;
String startDate;
int earnings;
public employee(String ID,String Name,String dept,String sDate,int earn){
empName = Name;
empID = ID;
department = dept;
startDate = sDate;
earnings = earn;
}
public employee( String ID, String Name) {
empName = Name;
empID = ID;
department = "";
startDate = "";
earnings = 0;
}
public employee(){
empName = "";
empID = "";
department = "";
startDate = "";
earnings = 0;
}
}
private static String[] fillDataArray() throws FileNotFoundException {
File DatabaseFile = new File("EmpDB_lab7.csv");
Scanner inputFile = new Scanner(DatabaseFile);
String InputLine;
String [] empDBTemp = null;
int i=0;
while (inputFile.hasNextLine()) {
InputLine = inputFile.nextLine();
empDBTemp = InputLine.split("-");
empID[i] = empDBTemp[1];
empName[i] = empDBTemp[2];
department[i] = empDBTemp[3];
startDate[i] = empDBTemp[4];
earnings[i] = empDBTemp[5];
}
return empDBTemp;
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at employeedb.EmployeeDB.fillDataArray(EmployeeDB.java:76)
at employeedb.EmployeeDB.main(EmployeeDB.java:28)
Java Result: 1

CSV parsing is harder than it appears, so you should use a pre-existing library, such as Super CSV
Your CSV column names should match your bean field names (or skip the header altogether), and earnings could be a String, else you'll want to use a CellProcessor to parse it.
Reading stuff into an array and stream processing are contradictory.
ICsvBeanReader csvReader = new CsvBeanReader(new FileReader("employeedatabase.csv"), CsvPreference.STANDARD_PREFERENCE);
String[] header = csvReader.getHeader(false);
EmployeeDB employeeDB;
while((employeeDB = csvReader.read(EmployeeDB.class, header)) != null) {
System.out.println(employeeDB.getEmpName());
}
csvReader.close();
And
public class EmployeeDB {
private String empID;
private String empName;
private String department;
private String startDate;
private String earnings;
...getters/setters...
}
I changed the header to:
EmpID,EmpName,Department,StartDate,Earnings

Related

Sort csv columns in alphabetical order and print out (JAVA)

List<String> ret = new ArrayList<>();
BufferedReader r = new BufferedReader(new InputStreamReader(str));
Stream lines = r.lines().skip(1);
lines.forEachOrdered(
line -> {
line= ((String) line).replace("\"", "");
ret.add((String) line);
The above code prints out all the data from csv file and looks something like this
Employee, id, address,
Jon, 2034, 4 main av,
How can I get it to print out the columns in alphabetical order?
so it should look like this
address, employee, id,
4 main av, Jon, 2034,
I suggest introducing some new class and overriding it's toString method and specify the order to be printed there and handle like below
This should work
public class Example {
public static void main(String[] args) throws FileNotFoundException {
List<String> ret;
File file = new File("/Users/A.csv");
InputStream targetStream = new FileInputStream(file);
BufferedReader r = new BufferedReader(new InputStreamReader(targetStream));
ret = r.lines().skip(1).map(line -> new Person(line).toString()).collect(Collectors.toList());
System.out.println(ret);
}
static class Person {
private String id;
private String employee;
private String address;
public Person(String line) {
String[] lineParts = line.replace("\"", "").split(",");
this.employee = lineParts[0];
this.id = lineParts[1];
this.address = lineParts[2];
}
#Override
public String toString() {
return String.join(",", this.address, this.employee, this.id);
}
}
}
static class Person {
private String id;
private String employee;
private String address;
public Person(String line) {
String[] lineParts = line.replace("\"", "").split(",");
this.employee = lineParts[0];
this.id = lineParts[1];
this.address = lineParts[2];
}
#Override
public String toString() {
return String.join(",", this.address, this.employee, this.id);
}
}

Java reading CSV file that contains Strings and Integers adding them to arraylist and then instantiating arraylist

SO, here goes my choppy explanation of my choppy title.
I have a csv file, and it contains, at the moment
id,name,hp,atk,def,desc
1,Man,10,5,5,A man
2,Woman,10,5,5,A woman
3,Goblin,15,7,3,A goblin ack!
I am trying to take the information from this csv file, send it to an ArrayList, instantiate the ArrayList using the Constructor I have for NPCs so that later on I can use these NPCs as objects -- if that makes sense.
I think I have like some of this done already, I just don't know how to read integers from the CSV file.
public class NPCLoader {
private static final String dir = "./data/npcs.csv";
public static ArrayList<NPCHandler> npcs = new ArrayList<NPCHandler>();
public static void main(String args[]) {
loadNpcs();
}
private static void loadNpcs() {
BufferedReader br = new BufferedReader(new FileReader(new File(dir)));
String line = null;
while((line = br.readLine()) != null) {
String[] n = line.split(",");
NPCHandler npc = new NPCHandler(n[0], n[1], n[2], n[3], n[4], n[5]);//issue is here, it wants me to change my constructor to String String String String String when it needs to be int String int int int String
npcs.add(npc);
}
}
}
Here is my constructor for the NPCHandler if you need to see it
public class NPCHandler {
private int id;
private String name;
private int hp;
private int atk;
private int def;
private String desc;
public NPCHandler(int id, String name, int hp, int atk, int def, String desc) {
this.id = id;
this.name = name;
this.hp = hp;
this.atk = atk;
this.def = def;
this.desc = desc;
}
//Get setters below
I think that since you're loading a csv file, every variables are considered strings.
The solution could be to parse some of them to Integer, something like that:
NPCHandler npc = new NPCHandler(Integer.parseInt(n[0]),
n[1],
Integer.parseInt(n[2]),
Integer.parseInt(n[3]),
Integer.parseInt(n[4]),
n[5]);
Reference for string conversion

Storing Objects in Linked List

I am creating a simple program which reads data from a text file and displays it in the console. The data that I am displaying is information regarding a student - name, id, subject, marks etc
The program reads the text file, and creates a student object for each user found. I am running into a problem when trying to store these students in a linked list. It seems to create a new list each time and overrides the previous one, so I always just end up with one student in the list.
How can I get it store them without overriding previous lists? Here is some of my code below:
public static boolean readFile(String filename) {
File file = new File(filename);
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
String[] words = scanner.nextLine().split(",");
int id = Integer.parseInt(words[0]);
String firstName = words[1];
String lastName = words[2];
int mathMark1 = Integer.parseInt(words[3]);
int mathMark2 = Integer.parseInt(words[4]);
int mathMark3 = Integer.parseInt(words[5]);
int englishMark1 = Integer.parseInt(words[6]);
int englishMark2 = Integer.parseInt(words[7]);
int englishMark3 = Integer.parseInt(words[8]);
addStudent(id,firstName,lastName,mathMark1,mathMark2,mathMark3,englishMark1,englishMark2,englishMark3);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("Failed to read file");
}
return true;
}
private static void addStudent(int id, String firstName, String lastName,int
mathsMark1, int mathsMark2, int mathsMark3, int englishMark1, int englishMark2,
int englishMark3) {
LinkedList<Student> student = new LinkedList<>();
student.add(new Student(id,firstName,lastName));
LinkedList<AssignmentMarks> mathematicsMarks = new LinkedList<>();
mathematicsMarks.add(new AssignmentMarks("Mathematics",mathsMark1,mathsMark2,mathsMark3));
LinkedList<AssignmentMarks> englishMarks = new LinkedList<>();
englishMarks.add(new AssignmentMarks("English",englishMark1,englishMark2,englishMark3));
}
This code above is in my Main class. The code below is from my Student class:
public class Student {
private int id;
private String firstName;
private String lastName;
private AssignmentMarks mathMarks;
private AssignmentMarks englishMarks;
public Student(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public String getFullName() {
return firstName;
}
}
Any help would be appreciated thanks guys!
This variable
LinkedList<Student> student = new LinkedList<>();
needs to declared outside of the method, as a field, or within readFile and passed in as a parameter, otherwise it will be created everytime that you call addStudent
Declare your LinkedList as a member of the class, because here every time you call addStudent() you are creating a new list.
You should instead do something like :
public class Test {
private LinkedList<Student> student = new LinkedList<>();
public static boolean readFile(String filename) {
// ...
addStudent(id,firstName,lastName,mathMark1,mathMark2,mathMark3,
englishMark1,englishMark2,englishMark3);
}
private static void addStudent(int id, String firstName, String lastName,int
mathsMark1, int mathsMark2, int mathsMark3, int englishMark1, int englishMark2,
int englishMark3) {
// ...
// this will now add it to the only instance of the list
student.add(new Student(id,firstName,lastName));
}
}

Separate data and store in ArrayList?

I am trying to separate a set of data. I need to store each data into a variable then create an object and put them in an ArrayList.
The dataset is in this format
lastName, firstName
ID num_courses
course1_name
grade units
course2_name
grade units
....
I have done this so far but I'm having trouble creating multiple objects, storing the data, and adding it to an ArrayList[]. Thanks for your time and help (:
public static void main (String[] args) throws FileNotFoundException {
Scanner scnr = new Scanner(System.in);
System.out.println("Enter file name: ");
String fileName = scnr.nextLine();
Scanner inFile = new Scanner(new FileInputStream(fileName)); //importing filename
ArrayList<String> list = new ArrayList<String>(); //for list of courses
String name = "";
String id = "";
int coursesTaken = 0;
String courseName = "";
char grade;
int courseUnit = 0;
while(inFile.hasNextLine()){
name = inFile.nextLine(); //first line is name
StringTokenizer st = new StringTokenizer(inFile.nextLine()); //separting whitespace
id = st.nextToken(); //storing ID
coursesTaken = Integer.parseInt(st.nextToken()); //storing num_courses_taken
Student s1 = new Student(name, id); //FIXME (need more than 1 student object)
for(int i = 0; i < coursesTaken*2; ++i){
courseName = inFile.nextLine();
s1.addCourses(courseName); //adding to arrayList
StringTokenizer st2 = new StringTokenizer(inFile.nextLine());
grade = st2.nextToken().charAt(0);
courseUnit = Integer.parseInt(st2.nextToken());
Course ci = new Course(courseName, grade, courseUnit); //FIXME (need more than 1 course)
}
}
}
Course.java
public class Course {
private String name;
private char grade;
private int units;
//constructors
public Course(){
name = "";
grade = 0;
units = 0;
}
public Course(String name, char grade, int units){
this.name = name;
this.grade = grade;
this.units = units;
}
//getters
public String getName(){
return name;
}
public char getGrade(){
return grade;
}
public int getUnits(){
return units;
}
//setters
public void setName(String name){
this.name = name;
}
public void setGrade(char grade){
this.grade = grade;
}
public void setUnits(int units){
this.units = units;
}
}
Student.java
public class Student {
private String name;
private String id;
private ArrayList<String> listCourses = new ArrayList<String>();
//constructor
//default
public Student(){
name = "none";
id = "none";
//courses = "none";
}
public Student(String name, String id){
this.name = name;
this.id = id;
//this.courses = courses;
}
//getters
public String getName(){
return name;
}
public String getId(){
return id;
}
public ArrayList<String> getCourses(){
return listCourses;
}
//setters
public void setName(String name){
this.name = name;
}
public void setId (String id){
this.id = id;
}
public void addCourses(String courses){
listCourses.add(courses);
}
}
First, you need a List to store your students:
ArrayList<Student> students = new ArrayList<>();
You should add each created student to this list when all fields are parsed:
students.add(s1);
Second, I think, it's better to change the listCourses field from ArrayList<String> to ArrayList<Course> - to store information about all students courses inside the Student object.
Third, you don't need to multiply coursesTaken by 2 because you call inFile.nextLine() twice for each course taken.
for (int i = 0; i < coursesTaken; i++)
Finally your main method would look like this:
private ArrayList<Course> listCourses = new ArrayList<>();
ArrayList<Student> students = new ArrayList<>();
while(inFile.hasNextLine()){
name = inFile.nextLine(); //first line is name
StringTokenizer st = new StringTokenizer(inFile.nextLine()); //separting whitespace
id = st.nextToken(); //storing ID
coursesTaken = Integer.parseInt(st.nextToken()); //storing num_courses_taken
Student s1 = new Student(name, id);
ArrayList<Course> courses = new ArrayList<>();
for(int i = 0; i < coursesTaken; i++){
courseName = inFile.nextLine();
StringTokenizer st2 = new StringTokenizer(inFile.nextLine());
grade = st2.nextToken().charAt(0);
courseUnit = Integer.parseInt(st2.nextToken());
courses.add(new Course(courseName, grade, courseUnit)); //FIXED
}
s1.setListCourses(courses);
students.add(s1); //FIXED
}
UPDATE: Changes in Student class:
public class Student {
private String name;
private String id;
private ArrayList<Course> listCourses = new ArrayList<>();
...
// this is just a setter for listCourses field
public void setListCourses(ArrayList<Course> listCourses) {
this.listCourses = listCourses;
}
}
//for list of courses
That's a list of strings.
This is for a list of courses
List<Course> list = new ArrayList<>();
Then, just list.add(ci) in the loop
Sidenote: Student.addCourses should be singular, and probably accept a Course object

conflict b/w string and string[]

Basically I have a class that has methods which use String arrays and i'm writing a method in the application class to read a file and update an array of object of class Customer. I get errors like:
Line 83: set_address(java.lang.String[]) in Customer cannot be applied to (java.lang.String)
at the line review[i].set_address(st[1]). I understand that it is looking for a string[] and it is receiving a string but is there any way to fix this? Here's the code I'm working with.
import java.io.*;
import java.util.*;
class Customer {
int account_id;
char[] ch1 = new char[20];
String name = new String (ch1);
char[] ch2 = new char[80];
String address = new String (ch2);
char[] ch3 = new char[10];
String phone_number = new String (ch3);
char[] ch4 = new char[8];
String date_of_birth = new String (ch4);
double account_balance;
public int get_accountid(){
return account_id;
}
public String get_address(){
return address;
}
public String get_phone_number(){
return phone_number;
}
public String get_date_of_birth(){
return date_of_birth;
}
public double get_balance(){
return account_balance;
}
public void set_account_id(int num){
account_id = num;
}
public void set_address(String add){
address = add;
}
public void set_phone_number(String phone){
phone_number = phone;
}
public void set_date_of_birth(String dob){
date_of_birth = dob;
}
public void set_balance(double bal){
account_balance = bal;
}
Customer(){ // default constructor
}
// parametrized constructor
Customer(int id, String name, String add, String dob, String num, double bal){
this.account_id = id;
this.name = name;
this.address = add;
this.date_of_birth = dob;
this.phone_number = num;
this.account_balance = bal;
}
}
public class lab2{
public static void main(String args[]){
System.out.println("testing this shit");
}
public static void readFile(String filename){
Customer[] review = new Customer[30];
int i=0;
Scanner scan = new Scanner (new File (filename));
while (scan.hasNext()){
while(i<30){
review[i].set_account_id(scan.nextInt());
String[] st = scan.nextLine().split("=");
review[i].set_address(st[1]);
st = scan.nextLine().spilt("=");
review[i].set_phone_number(st[1]);
st = scan.nextLine().split("=");
review[i].set_date_of_birth(st[1]);
//st = scan.nextLine().split("=");
review[i].set_balance(scan.nextDouble());
scan.nextLine();
i=i+1;
}
}
}
}
Your class Customer looks like a Java bean. I find these declaration suspicious:
String[] name = new String [20];
String[] address = new String [80];
String[] phone_number = new String [10];
String[] date_of_birth = new String [8];
Why do you want a Customer to have 20 names, 80 addresses, 10 phone numbers, and 8 date of birth? I suspect that your intention is saying that a Customer name is at most 20 characters long, his/her address is at most 80 characters long, etc. If this is the case, than you don't want a String[], you may want a char[]!
However, think about making those fields simply String: it seems more natural. I don't see reason why you may want to limit their size.
Just change your method signature:
public void set_address(String add){
address = add;
}
Or other choice: You create a new String[] object based on your String object an pass this:

Categories