my question is short how write new class which will take info from main class List and print ir into a new file?
So this is my my ProgramTest class, which are main:
public class ProgramTest {
public static void main(String [] args)throws Exception {
//Autoriai
Author authorInf00 = new Author ("Mykolas", "Razma");
Author authorInf01 = new Author ("Lukas", "Brazukas");
Author authorInf02 = new Author ("Kristijonas", "Stoma");
//Knygos
Book bookInf00 = new Book ("Mykolas", "Razma", "Paukstis", 11111111, authorInf00);
Book bookInf01 = new Book ("Kristijonas", "Stoma", "gandras", 2222222, authorInf01);
Book bookInf02 = new Book ("Lukas", "Brazukas", "Varna", 3333333, authorInf02);
//Knygu listas
List <String> bookList = new ArrayList <String>();
bookList.add(bookInf00.getName() + " " + bookInf00.getIsbn() + " " + bookInf00.getFirstName() + " " + bookInf00.getLastName());
bookList.add(bookInf01.getName() + " " + bookInf01.getIsbn() + " " + bookInf01.getFirstName() + " " + bookInf01.getLastName());
bookList.add(bookInf02.getName() + " " + bookInf02.getIsbn() + " " + bookInf02.getFirstName() + " " + bookInf02.getLastName());
//Isveda i konsole Knygu lista
System.out.println("Knyga ISBN Vardas Pavarde");
for(int i=0; i < bookList.size();i++)
{
System.out.println(bookList.get(i));
}
//Sukuria instrukcija
Txt xce = new Txt();
//Paleidzia dirbti xml writeri
xce.runExample();
}
}
The second class is Library:
import java.util.List;
public class Library {
private List <String> bookList;
private DataWriter dataWriter;
public List <String> getBookList(){
return bookList;
}
public void exportBookList (List <String> bookList){
this.bookList = bookList;
}
public void setDataWriter(DataWriter dataWriter) {
this.dataWriter = dataWriter;
}
public DataWriter getDataWriter() {
return dataWriter;
}
}
DataWriter which should write info into file
import java.util.List;
public interface DataWriter {
public void dataWriterBook(List<String> bookList);
}
That is the problem: don't know how to write it correctly that it print my list into file.txt
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Txt {
public void runExample(){
System.out.println("Started .. ");
createDOMTree();
printToFile();
List <String> bookList;
System.out.println("Generated file successfully.");
}
public void dataWriterBook(List <String> bookList){
}
public void printToFile(){
try {
List<String> bookList = new ArrayList<String>();
// obviously you would want to use a list with stuff in it
BufferedWriter out = new BufferedWriter(
new FileWriter("C:/Users/jjegorovas/xml_failas.xml"));
for (String item : bookList){
out.write(item);
out.newLine();
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can make a List of Books and then override the toString() methode.
For example:
class Book
{
private string name;
private string author;
private int id;
public Book(string name, string author, int id)
{
this.name = name;
this.author = author;
this.id = id;
}
public String toString()
{
return id + " - " + name + " - " + author; //Maybe use StringBuilder
}
}
class Main()
{
public static void main(String [] args)
{
Book book1 = new Book("Book1","James",1);
Book book2 = new Book("Book2","John",2);
Book book3 = new Book("Book2","Smith",3);
List<Book> bookList = new ArrayList<Book>();
bookList.add(book1);
bookList.add(book2);
bookList.add(book3);
saveBooksToFile(bookList);
}
public static void saveBooksToFile(List<Book> bookList)
{
//better use try-with-resource here
try {
BufferedWriter out = new BufferedWriter(
new FileWriter("C:/Users/jjegorovas/xml_failas.xml"));
for (Book book : bookList){
out.write(book.toString());
out.newLine();
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In ProgramTest.java, pass the bookList to Txt constructor as shown below:
//Sukuria instrukcija
Txt xce = new Txt( bookList); //pass bookList
//Paleidzia dirbti xml writeri
xce.runExample();
Modify Txt.java, as below (explanations in comments):
public class Txt {
List<String> bookList; //add a field to store the book list
public Txt(List<String> bookList) { //add a constructor method
this.bookList = bookList;
}
public void printToFile() { //modify this method
try {
BufferedWriter out = new BufferedWriter(new FileWriter(
"C:/Users/jjegorovas/xml_failas.txt")); //change extension from XML to TXT
for (String item : bookList) {
out.write(item);
out.newLine();
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
I am not too familiar with polymorphism, and was wondering if I have it used in my code?
If this doesn't contain a polymorphic reference, could you lead me in a direction of where I would need to go? The files that the program is using are not included, as I am mainly curious about whether or not any polymorphic references are used.
java file 1 - this file runs the program
import java.util.Scanner;
public class ADTDemo {
ADTDictionary dictionary;
public static void menu() {
System.out.println("Welcome the Faculty Directory Program");
System.out.println(" Use commands:");
System.out.println(" list all");
System.out.println(" list DEPT_NAME");
System.out.println(" add DEPT_NAME, FIRST LAST");
System.out.println(" remove DEPT_NAME, FIRST LAST");
System.out.println(" exit");
}
public static void main(String[] args) {
menu();
String command;
ADTDemo dictObj = new ADTDemo();
dictObj.dictionary = new ADTDictionary();
dictObj.dictionary.read();
Scanner scanner = new Scanner(System.in);
do {
System.out.println("");
System.out.print(">>");
command = scanner.nextLine().trim();
if (!command.equals("exit")) {
dictObj.action(command);
} else {
dictObj.dictionary.saveEntries();
System.out.println("Goodbye! Have a nice day!");
}
} while (!command.equalsIgnoreCase("exit"));
}
public void action(String command) {
if (command.equalsIgnoreCase("LIST ALL")) {
dictionary.listAll();
return;
}
else if (command.toUpperCase().contains("LIST")) {
if (command.length() == 4){
System.out.println("Command needed.");
return;
}
command = command.substring(5, command.length());
dictionary.listDeptName(command);
return;
}
else if (command.toUpperCase().contains("ADD")) {
command = command.substring(4, command.length());
dictionary.add(command);
return;
}
else if (command.toUpperCase().contains("REMOVE")) {
command = command.substring(6, command.length());
dictionary.remove(command);
}
}
}
java file 2
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class ADTDictionary {
Map<String, List<String>> adtDictionary;
public void read() {
try {
File facultyFile = new File("faculty.txt");
File departmentFile = new File("departments.txt");
Scanner departmentScanner = new Scanner(departmentFile);
Scanner facultyScanner = new Scanner(facultyFile);
adtDictionary = new HashMap<String, List<String>>();
while (departmentScanner.hasNextLine()) {
String department = departmentScanner.nextLine().trim();
adtDictionary.put(department, new ArrayList<String>());
}
while (facultyScanner.hasNextLine()) {
String faculty = facultyScanner.nextLine();
String[] values = faculty.split(",");
adtDictionary.get(values[1].trim()).add(values[0]);
}
} catch (FileNotFoundException ex) {
System.out.println("ERROR: File not found.");
}
}
public void listAll() {
for (String key : adtDictionary.keySet()) {
for (String value : adtDictionary.get(key)) {
System.out.println(value + ", " + key);
}
}
}
public void listDeptName(String department) {
if (null != adtDictionary.get(department)) {
for (String name : adtDictionary.get(department)) {
System.out.println(name);
}
}
else{
System.out.println("Unknown entry made.");
}
}
public void add(String value) {
if(!value.contains(",")){
System.out.println("Incorrect entry.");
return;
}
String[] values = value.split(",");
String dept = values[0].trim();
String faculty = values[1].trim();
String[] facName = faculty.split(" ");
if (!(facName.length == 2)){
System.out.println("Please only enter First and Last name of faculty member.");
return;
}
if (!(null != adtDictionary.get(dept))) {
if(adtDictionary.containsKey(dept.toUpperCase())){
System.out.println("Incorrect departtment entry.");
return;
}
else if (dept == dept.toUpperCase()){
adtDictionary.put(dept, new ArrayList<String>());
}
else{
System.out.println("Incorrect department entry.");
return;
}
}
for (String name : adtDictionary.get(dept)) {
if (name.equalsIgnoreCase(faculty)) {
System.out.println("Cannot add " + name + " to " + dept + " because they already exist there.");
return;
}
}
adtDictionary.get(dept).add(faculty);
System.out.println("OK, added " + faculty);
}
public void remove(String value) {
String[] values = value.split(",");
String dept = values[0].trim();
String faculty = values[1].trim();
adtDictionary.get(dept).remove(faculty);
System.out.println("OK, removed " + faculty + " from " + dept);
}
public void saveEntries(){
try {
File facultyFile = new File("faculty.txt");
File departmentFile = new File("departments.txt");
PrintWriter facWriter = new PrintWriter(facultyFile);
PrintWriter deptWriter = new PrintWriter(departmentFile);
for (Object s : adtDictionary.keySet()) {
deptWriter.println(s);
}
deptWriter.close();
for (String key : adtDictionary.keySet()) {
for (String value : adtDictionary.get(key)) {
facWriter.println(value + ", " + key);
}
}
facWriter.close();
}
catch (IOException ex){
System.out.println("ERROR saving file.");
}
}
}
i have a method that puts some value(obtained from an excel file) into a hashmap with an array as the key
public HashMap<List<String>, List<String[]>> sbsBusServiceDataGnr() throws
IOException
{
System.out.println(engine.txtY + "Processing HashMap "
+ "sbsBusServiceData..." + engine.txtN);
int counterPass = 0, counterFail = 0, stopCounter = 0;
String dataExtract, x = "";
String[] stopInfo = new String[3];
List<String[]> stopsData = new ArrayList<String[]>();
List<String> serviceNum = new Vector<String>();
HashMap<List<String>, List<String[]>> sbsBusServiceData =
new HashMap<List<String>, List<String[]>>();
String dataPath = this.dynamicPathFinder(
"Data\\SBS_Bus_Routes.csv");
BufferedReader sbsBusServiceDataPop = new BufferedReader(
new FileReader(dataPath));
sbsBusServiceDataPop.readLine();
//Skips first line
while ((dataExtract = sbsBusServiceDataPop.readLine()) != null) {
try {
String[] dataParts = dataExtract.split(",", 5);
if (!dataParts[4].equals("-")){
if (Double.parseDouble(dataParts[4]) == 0.0){
sbsBusServiceData.put(serviceNum, stopsData);
String serviceNum1 = "null", serviceNum2 = "null";
if(!serviceNum.isEmpty()){
serviceNum1 = serviceNum.get(0);
serviceNum2 = serviceNum.get(1);
}
System.out.println("Service Number " + serviceNum1
+ ":" + serviceNum2 + " with " + stopCounter
+ " stops added.");
stopCounter = 0;
//Finalizing previous service
serviceNum.Clear();
serviceNum.add(0, dataParts[0]);
serviceNum.add(1, dataParts[1]);
//Adding new service
}
}
stopInfo[0] = dataParts[2];
stopInfo[1] = dataParts[3];
stopInfo[2] = dataParts[4];
stopsData.add(stopInfo);
//Adding stop to service
stopCounter++;
counterPass++;
}
catch (Exception e) {
System.out.println(engine.txtR + "Unable to process "
+ dataExtract + " into HashMap sbsBusServiceData."
+ engine.txtN + e);
counterFail++;
}
}
sbsBusServiceDataPop.close();
System.out.println(engine.txtG + counterPass + " number of lines"
+ " processed into HashMap sbsBusServiceData.\n" + engine.txtR
+ counterFail + " number of lines failed to process into "
+ "HashMap sbsBusServiceData.");
return sbsBusServiceData;
}
//Generates sbsBusServiceDataGnr HashMap : 15376 Data Rows
//HashMap Contents: {ServiceNumber, Direction},
// <{RouteSequence, bsCode, Distance}>
this method work for putting the values into the hashmap but i cannot seem to get any value from the hashmap when i try to call it there is always a nullpointerexception
List<String> sbsTest = new Vector<String>();
sbsTest.add(0, "10");
sbsTest.add(1, "1");
System.out.println(sbsBusServiceData.get(sbsTest));
try{
List<String[]> sbsServiceResults = sbsBusServiceData.get(sbsTest);
System.out.println(sbsServiceResults.size());
String x = sbsServiceResults.get(1)[0];
System.out.println(x);
} catch(Exception e){
System.out.println(txtR + "No data returned" + txtN + e);
}
this is a sample of the file im reading the data from:
SBS
How can i get the hashmap to return me the value i want?
Arrays are not suitable as keys in HashMaps, since arrays don't override Object's equals and hashCode methods (which means two different array instances containing the exact same elements will be considered as different keys by HashMap).
The alternatives are to use a List<String> instead of String[] as the key of the HashMap, or to use a TreeMap<String[]> with a custom Comparator<String[]> passed to the constructor.
If you are having fixed array size then the example I'm posting might be useful.
Here I've created two Object one is Food and Next is Product.
Here Food object is use and added method to get string array.
public class Product {
private String productName;
private String productCode;
public Product(String productName, String productCode) {
this.productName = productName;
this.productCode = productCode;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
}
Food Model Class: Use as a Object instead of String[] and achieve String[] functionality.
public class Food implements Comparable<Food> {
private String type;
private String consumeApproach;
public Food(String type, String consumeApproach) {
this.type = type;
this.consumeApproach = consumeApproach;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getConsumeApproach() {
return consumeApproach;
}
public void setConsumeApproach(String consumeApproach) {
this.consumeApproach = consumeApproach;
}
public String[] FoodArray() {
return new String[] { this.type, this.consumeApproach };
}
//Implement compareTo method as you want.
#Override
public int compareTo(Food o) {
return o.getType().compareTo(this.type);
}
}
Using HashMap example
public class HashMapKeyAsArray {
public static void main(String[] args) {
HashMap<Food,List<Product>> map = dataSetLake();
map.entrySet().stream().forEach(m -> {
String[] food = m.getKey().FoodArray();
Arrays.asList(food).stream().forEach(f->{
System.out.print(f + " ");
});
System.out.println();
List<Product> list = m.getValue();
list.stream().forEach(e -> {
System.out.println("Name:" + e.getProductName() + " Produc Code:" + e.getProductCode());
});
System.out.println();
});
}
private static HashMap<Food,List<Product>> dataSetLake(){
HashMap<Food,List<Product>> data = new HashMap<>();
List<Product> fruitA = new ArrayList<>();
fruitA.add(new Product("Apple","123"));
fruitA.add(new Product("Banana","456"));
List<Product> vegetableA = new ArrayList<>();
vegetableA.add(new Product("Potato","999"));
vegetableA.add(new Product("Tomato","987"));
List<Product> fruitB = new ArrayList<>();
fruitB.add(new Product("Apple","123"));
fruitB.add(new Product("Banana","456"));
List<Product> vegetableB = new ArrayList<>();
vegetableB.add(new Product("Potato","999"));
vegetableB.add(new Product("Tomato","987"));
Food foodA = new Food("Fruits","Read To Eat");
Food foodB = new Food("Vegetables","Need To Cook");
Food foodC = new Food("VegetablesC","Need To Cook C");
data.put(foodA, fruitB);
data.put(foodB, vegetableB);
data.put(foodA, fruitA);
data.put(foodC, vegetableA);
return data;
}
Using TreeMap example
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;
public class TreeMapKeyAsArray {
public static void main(String[] args) {
TreeMap<Food, List<Product>> map = dataSetLake();
map.entrySet().stream().forEach(m -> {
String[] food = m.getKey().FoodArray();
Arrays.asList(food).stream().forEach(f->{
System.out.print(f + " ");
});
System.out.println();
List<Product> list = m.getValue();
list.stream().forEach(e -> {
System.out.println("Name:" + e.getProductName() + " Produc Code:" + e.getProductCode());
});
System.out.println();
});
}
private static TreeMap<Food, List<Product>> dataSetLake() {
TreeMap<Food, List<Product>> data = new TreeMap<>();
List<Product> fruitA = new ArrayList<>();
fruitA.add(new Product("Apple", "123"));
fruitA.add(new Product("Banana", "456"));
List<Product> vegetableA = new ArrayList<>();
vegetableA.add(new Product("Potato", "999"));
vegetableA.add(new Product("Tomato", "987"));
List<Product> fruitB = new ArrayList<>();
fruitB.add(new Product("Apple", "123"));
fruitB.add(new Product("Banana", "456"));
List<Product> vegetableB = new ArrayList<>();
vegetableB.add(new Product("Potato", "999"));
vegetableB.add(new Product("Tomato", "987"));
Food foodA = new Food("Fruits", "Read To Eat");
Food foodB = new Food("Vegetables", "Need To Cook");
data.put(foodA, fruitB);
data.put(foodB, vegetableB);
data.put(foodA, fruitA);
data.put(foodB, vegetableA);
return data;
}
}
I have a 'Person' class where i stored data like name, surname etc. I make 5 object type Person, add them to ArrayList, and save this ArrayList to file. Next i'm loading from this file ArrayList and i have 5 person. Problem is when i want save again for example 10 object Person. When i'm loading ArrayList from file i'm getting only 5 person from first writing. If i repeat this still i will have load data from first writing to this file. How i can fix this ?
public class Data {
static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
Data.savePersons(5);
Data.loadPersons();
/** Clean 'persons' array for TEST of load data */
persons.removeAll(persons);
System.out.println("\n-----------\nNext Round\n-----------\n");
Data.savePersons(10);
Data.loadPersons();
}
/** Save a couple of Person Object to file C:/data.ser */
public static void savePersons(int noOfPersonToSave) throws IOException {
FileOutputStream fout = null;
ObjectOutputStream oos = null;
/** Make 5 'Person' object and add them to ArrayList 'persons' for example */
for (int i = 0; i < noOfPersonToSave; i++) {
Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890" +i);
persons.add(personTest);
}
try {
fout = new FileOutputStream("C:\\data.ser", true);
oos = new ObjectOutputStream(fout);
oos.writeObject(persons);
System.out.println("Saving '" + persons.size() + "' Object to Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR: " + ex.getMessage());
} finally {
if (oos != null) {
oos.close();
}
}
}
/** Load previously saved a couple of Person Object in file C:/data.ser */
public static void loadPersons() throws IOException {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("C:\\data.ser");
ois = new ObjectInputStream(fis);
persons = (List<Person>) ois.readObject();
//persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" + persons.size() + "' Object from Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("loadPersons() = OK");
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR: " + e.getMessage());
} finally {
if (ois != null) {
ois.close();
}
}
}}
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String surname;
private String mail;
private String telephone;
public Person(String n, String s, String m, String t) {
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}}
new FileOutputStream("C:\\data.ser", true)
You're passing true for the append parameter. So you're appending a list of 10 persons to the file, after the already existing list of 5 people. And since you only read one list, you read the first you wrote, which contains 5 persons.
Pass false instead of true.
DESCRIPTION:
In my program, users are asked to input some values. The values get stored into an ArrayList so that I can print them out. Now the problem with this one is all data is lost once I terminate the program. That's why I have decided to store those arrayList object into file and and read them from there.
PROBLEM/QUESTION:
I have created all the related methods to write and read file. But it seems that no objects are written and read in file.The class I am mainly concerned about is ReadWrite.
Working code:
ReadWrite:
public void writeFile(List<PersonInfo> information) {
try {
FileOutputStream fos = new FileOutputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile4.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(information);
os.flush();
fos.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<PersonInfo> readFile() {
List<PersonInfo> dataFromFile=null;
try {
FileInputStream fis = new FileInputStream("C:\\Users\\Documents\\NetBeansProjects\\BankFile4.txt");
ObjectInputStream is = new ObjectInputStream(fis);
dataFromFile=(List<PersonInfo>)is.readObject();
fis.close();
is.close();
//return readFile();
} catch (Exception e) {
e.printStackTrace();
}
return dataFromFile;
}
AboutPerson:
Scanner input = new Scanner(System.in);
List<PersonInfo> info = new ArrayList<PersonInfo>();
List<PersonInfo> info2 = new ArrayList<PersonInfo>();
ReadWrite rw=new ReadWrite();
rw.writeFile(info);
info2=rw.readFile();
while (true) {
System.out.println("\n");
System.out.println("1. Input personal info\n"
+ "2. Print them out\n"
+ "*************"
+ "*************");
option1 = input.nextInt();
input.nextLine();
switch (option1) {
case 1:
PersonInfo personInfo = new PersonInfo();
//take the input
System.out.println("Enter a name: ");
personInfo.setName(input.nextLine());
System.out.println("Give ID: ");
personInfo.setId(input.nextInt());
System.out.println("Input credit: ");
personInfo.setCredit(input.nextDouble());
//addint them up
info.add(personInfo);
break;
case 2:
//display them
System.out.println("");
System.out.println("Name\t\tID\t\tCredit");
for (PersonInfo pInfo : info) {
System.out.println(pInfo);
}
System.out.println("\t\t.............\n"
+ "\t\t.............");
break;
}
}
PersonInfo:
........
........
public PersonInfo() {
this.name = null;
this.id = 0;
this.credit = 0;
}
public void setName(String name) {
this.name = name;
}
.........
.........
package com.collection;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class PersonInfo implements Serializable{
private String name;
private int id;
private double credit;
public PersonInfo(){}
public PersonInfo(String name,int id,int credit)
{
this.name=name;
this.id=id;
this.credit=credit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getCredit() {
return credit;
}
public void setCredit(double credit) {
this.credit = credit;
}
}
class ReadWrite
{
public void writeFile(List<PersonInfo> information){
try {
FileOutputStream fos = new FileOutputStream("/home/mohammad.sadik/TestReadWrite.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(information);
os.flush();
fos.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public List<PersonInfo> readFile() {
List<PersonInfo> dataFromFile=null;
try {
FileInputStream fis = new FileInputStream("/home/mohammad.sadik/TestReadWrite.txt");
ObjectInputStream is = new ObjectInputStream(fis);
dataFromFile=(List<PersonInfo>)is.readObject();
fis.close();
is.close();
//return readFile();
} catch (Exception e) {
e.printStackTrace();
}
return dataFromFile;
}
}
public class AboutPerson {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<PersonInfo> info = new ArrayList<PersonInfo>();
List<PersonInfo> info2 = new ArrayList<PersonInfo>();
ReadWrite rw=new ReadWrite();
while (true) {
System.out.println("\n");
System.out.println("1. Input personal info\n"
+ "2. Print them out\n"
+ "*************"
+ "*************");
int option1 = input.nextInt();
input.nextLine();
switch (option1) {
case 1:
PersonInfo personInfo = new PersonInfo();
//take the input
System.out.println("Enter a name: ");
personInfo.setName(input.nextLine());
System.out.println("Give ID: ");
personInfo.setId(input.nextInt());
System.out.println("Input credit: ");
personInfo.setCredit(input.nextDouble());
//addint them up
info.add(personInfo);
rw.writeFile(info);
break;
case 2:
//display them
info2=rw.readFile();
System.out.println("");
System.out.println("Name\t\tID\t\tCredit");
for (PersonInfo pinfo : info2) {
System.out.println(pinfo.getName()+"\t\t"+pinfo.getId()+"\t\t"+pinfo.getCredit());
}
System.out.println("\t\t.............\n"
+ "\t\t.............");
break;
}
}
}
}
Please implement serializable interface in PersonInf class.When u going to write object into file then u need to implement serializable interface other wise u will get exception like this:
java.io.NotSerializableException: com.collection.PersonInfo
first PersonInfo should implement SerialiZable,
and i'm not sure but PersonInfo should also have a default constructor
I'm creating an employee time clock for a java class. This portion of my program is for reporting an individual's time, and reporting all employees time. My code works well for the individual, but I'm having trouble converting it to work for all employees. Should I try looping through the whole file and retrieving as it goes? The information being inside a control statement is causing me problems. Also, to only look at a two-week period, would using calendar and date -14 days be a good way to accomplish that?
Any feedback on how to proceed appreciated.
package PunchinPunchout;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class IDchecker {
private static BufferedReader br;
private static BufferedReader br1;
static int total;
static int total1;
public static void main(String args[]) throws IOException {
getsubject();
}
public static void getsubject() throws FileNotFoundException, IOException {
ArrayList<Integer> totalhours = new ArrayList<>();
br = new BufferedReader(new FileReader("timeclock1.txt"));
br1 = new BufferedReader(new FileReader("newemployee8.txt"));
String line = "";
String line1 = "";
Scanner sc = new Scanner(System.in);
System.out.print("Enter an employee ID number: ");
String idnumber = sc.next();//read the choice
sc.nextLine();// discard any other data entered on the line
while ((line1 = br1.readLine()) != null) {
if (line1.contains(idnumber)) {
System.out.println("Employee Name & ID ");
System.out.println(line1);
}
}
while ((line = br.readLine()) != null) {
if (line.contains(idnumber + " ") && line.contains("in")) {
System.out.println();
System.out.println(" Date Time ID Punched");
System.out.println(line);
String regexp = "[\\s:\\n]+"; // these are my delimiters
String[] tokens; // here i will save tokens
for (int i = 0; i < 1; i++) {
tokens = line.split(regexp);
total = Integer.parseInt(tokens[1]);
}
} else if (line.contains(idnumber + " ") && line.contains("out")) {
System.out.println(line);
String regexp = "[\\s:\\n]+";
String[] tokens;
for (int i = 0; i < 1; i++) {
tokens = line.split(regexp);
total1 = Integer.parseInt(tokens[1]);
System.out.print("Total hours for " + tokens[0] + " are: ");
}
int dailytotal = total1 - total;
System.out.println(dailytotal + " hours");
totalhours.add(dailytotal);
}
}
System.out.println();
int sum = totalhours.stream().mapToInt(Integer::intValue).sum();
System.out.println("The total hours for the last two weeks is " + sum + " hours.");
}
}
*Output from timeclock1.txt
05/05/2014 05:00:00 508 in
05/05/2014 09:00:00 508 out
05/05/2014 03:00:00 509 in
05/05/2014 09:00:00 509 out
05/05/2014 03:00:00 510 in
05/05/2014 08:00:00 510 out
05/05/2014 08:00:00 511 in
05/05/2014 10:00:00 511 out
*Output from newemployee8.txt
james bush 10
bobby bush 11
john hunt 12
mick jag 13
jacob sanchez 14
Okay, this a little of an over the top example, but it highlights the power of a OO language like Java...
There are a number of ways that this might be achieved, based on your requirements. I've made a few assumptions (like a in is followed by an out for the same employee), but the basic gist is demonstrated.
The intention is centralise some of the functionality into re-usable and manageable blocks, reducing the code duplication. Access to the data is simplified and because it's done in memory, is faster...
To start with, you will want to create object representations of the employee and time clock data, this will make it easier to manager...
Employee Example
public class Employee {
private final int id;
private final String name;
public Employee(String text) {
String[] parts = text.split(" ");
id = Integer.parseInt(parts[2]);
name = parts[0] + " " + parts[1];
}
public String getName() {
return name;
}
public int getId() {
return id;
}
}
TimeClockEntry example
public class TimeClockEntry {
private Date inTime;
private Date outTime;
private int employeeID;
public TimeClockEntry(String text) throws ParseException {
String parts[] = text.split(" ");
employeeID = Integer.parseInt(parts[2]);
setClockTimeFrom(text);
}
public void setClockTimeFrom(String text) throws ParseException {
String parts[] = text.split(" ");
if ("in".equalsIgnoreCase(parts[3])) {
inTime = CLOCK_DATE_TIME_FORMAT.parse(parts[0] + " " + parts[1]);
} else if ("out".equalsIgnoreCase(parts[3])) {
outTime = CLOCK_DATE_TIME_FORMAT.parse(parts[0] + " " + parts[1]);
}
}
public int getEmployeeID() {
return employeeID;
}
public Date getInTime() {
return inTime;
}
public Date getOutTime() {
return outTime;
}
}
Now, we need some kind of "manager" to manage the details of these two classes, these managers should provide access methods which allow use to retrieve information that they manage. These managers will also be responsible for loading the data from the files...
EmployeeManager example
public class EmployeeManager {
private Map<Integer, Employee> employees;
public EmployeeManager() throws IOException {
employees = new HashMap<>(25);
try (BufferedReader br = new BufferedReader(new FileReader(new File("NewEmployee8.txt")))) {
String text = null;
while ((text = br.readLine()) != null) {
Employee emp = new Employee(text);
employees.put(emp.getId(), emp);
}
}
}
public List<Employee> getEmployees() {
return Collections.unmodifiableList(new ArrayList<Employee>(employees.values()));
}
public Employee getEmployee(int id) {
return employees.get(id);
}
}
TimeClockManager example
public class TimeClockManager {
private Map<Integer, List<TimeClockEntry>> timeClockEntries;
public TimeClockManager() throws IOException, ParseException {
timeClockEntries = new HashMap<>(25);
try (BufferedReader br = new BufferedReader(new FileReader(new File("TimeClock1.txt")))) {
String text = null;
TimeClockEntry entry = null;
int line = 0;
while ((text = br.readLine()) != null) {
if (line % 2 == 0) {
entry = new TimeClockEntry(text);
} else {
entry.setClockTimeFrom(text);
List<TimeClockEntry> empEntries = timeClockEntries.get(entry.getEmployeeID());
if (empEntries == null) {
empEntries = new ArrayList<>(25);
timeClockEntries.put(entry.getEmployeeID(), empEntries);
}
empEntries.add(entry);
}
line++;
}
}
}
public List<TimeClockEntry> getByEmployee(Employee emp) {
List<TimeClockEntry> list = timeClockEntries.get(emp.getId());
list = list == null ? new ArrayList<>() : list;
return Collections.unmodifiableList(list);
}
}
Now, internally, these managers are managing the data through the use of Maps, to make it easier to find data, specifically, this is most keyed on the employee's id
Now, once we have these, we can ask for information from the as we please...
public Report() {
try {
EmployeeManager empManager = new EmployeeManager();
TimeClockManager timeClockManager = new TimeClockManager();
for (Employee emp : empManager.getEmployees()) {
System.out.println("[" + emp.getId() + "] " + emp.getName());
for (TimeClockEntry tce : timeClockManager.getByEmployee(emp)) {
System.out.println(" "
+ CLOCK_DATE_TIME_FORMAT.format(tce.getInTime())
+ " to "
+ CLOCK_DATE_TIME_FORMAT.format(tce.getOutTime()));
}
}
} catch (IOException | ParseException exp) {
exp.printStackTrace();
}
}
Another approach would be to incorporate both managers into a single class. The basic idea would be to load the employee and time clock data, the time clock data would become a property of the Employee and you could simply be able to access it directly.
This is a slightly more elegant solution, as you have all the data contained within a single construct, but might not meet your needs
Fully runnable example
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import oracle.jrockit.jfr.parser.ParseException;
public class Report {
public static void main(String[] args) {
new Report();
}
public Report() {
try {
EmployeeManager empManager = new EmployeeManager();
TimeClockManager timeClockManager = new TimeClockManager();
for (Employee emp : empManager.getEmployees()) {
System.out.println("[" + emp.getId() + "] " + emp.getName());
for (TimeClockEntry tce : timeClockManager.getByEmployee(emp)) {
System.out.println(" "
+ CLOCK_DATE_TIME_FORMAT.format(tce.getInTime())
+ " to "
+ CLOCK_DATE_TIME_FORMAT.format(tce.getOutTime()));
}
}
} catch (IOException | ParseException exp) {
exp.printStackTrace();
}
}
public class EmployeeManager {
private Map<Integer, Employee> employees;
public EmployeeManager() throws IOException {
employees = new HashMap<>(25);
try (BufferedReader br = new BufferedReader(new FileReader(new File("NewEmployee8.txt")))) {
String text = null;
while ((text = br.readLine()) != null) {
if (!text.trim().isEmpty()) {
Employee emp = new Employee(text);
employees.put(emp.getId(), emp);
}
}
}
}
public List<Employee> getEmployees() {
return Collections.unmodifiableList(new ArrayList<Employee>(employees.values()));
}
public Employee getEmployee(int id) {
return employees.get(id);
}
}
public class TimeClockManager {
private Map<Integer, List<TimeClockEntry>> timeClockEntries;
public TimeClockManager() throws IOException, ParseException {
timeClockEntries = new HashMap<>(25);
try (BufferedReader br = new BufferedReader(new FileReader(new File("TimeClock1.txt")))) {
String text = null;
TimeClockEntry entry = null;
int line = 0;
while ((text = br.readLine()) != null) {
if (!text.trim().isEmpty()) {
if (line % 2 == 0) {
entry = new TimeClockEntry(text);
} else {
entry.setClockTimeFrom(text);
List<TimeClockEntry> empEntries = timeClockEntries.get(entry.getEmployeeID());
if (empEntries == null) {
empEntries = new ArrayList<>(25);
timeClockEntries.put(entry.getEmployeeID(), empEntries);
}
empEntries.add(entry);
}
line++;
}
}
}
}
public List<TimeClockEntry> getByEmployee(Employee emp) {
List<TimeClockEntry> list = timeClockEntries.get(emp.getId());
list = list == null ? new ArrayList<>() : list;
return Collections.unmodifiableList(list);
}
}
public class Employee {
private final int id;
private final String name;
public Employee(String text) {
System.out.println("[" + text + "]");
for (char c : text.toCharArray()) {
System.out.print((int) c + ",");
}
System.out.println("");
String[] parts = text.split("\\s+");
id = Integer.parseInt(parts[2]);
name = parts[0] + " " + parts[1];
}
public String getName() {
return name;
}
public int getId() {
return id;
}
}
public static final SimpleDateFormat CLOCK_DATE_TIME_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
public static final SimpleDateFormat CLOCK_DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
public class TimeClockEntry {
private Date inTime;
private Date outTime;
private int employeeID;
public TimeClockEntry(String text) throws ParseException {
System.out.println("[" + text + "]");
for (char c : text.toCharArray()) {
System.out.print((int) c + ",");
}
System.out.println("");
String parts[] = text.split("\\s+");
employeeID = Integer.parseInt(parts[2]);
setClockTimeFrom(text);
}
public void setClockTimeFrom(String text) throws ParseException {
String parts[] = text.split("\\s+");
if ("in".equalsIgnoreCase(parts[3])) {
inTime = CLOCK_DATE_TIME_FORMAT.parse(parts[0] + " " + parts[1]);
} else if ("out".equalsIgnoreCase(parts[3])) {
outTime = CLOCK_DATE_TIME_FORMAT.parse(parts[0] + " " + parts[1]);
}
}
public int getEmployeeID() {
return employeeID;
}
public Date getInTime() {
return inTime;
}
public Date getOutTime() {
return outTime;
}
}
}