Java: How to retrieve data from a control statement? - java

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

Related

group and sum sales in String array java

I have a text file as below:
Pen 100
Ink 50
Pen 150
Paper 20
and I want to sum each of the goods
the output should look like:
Pen 250
Ink 50
Paper 20
Max Pen 250
Min Paper 20
I write just only some code below and I stuck:
public static void readData(){
File infile = new File("D:\\itemData.txt");
String itemName = new String();
String[] nameList = new String[100];
String[] saleList = new String[100];
int sale;
int count =0;
try {
Scanner data = new Scanner(infile);
while (data.hasNext()) {
itemName = data.next();
sale = data.nextInt();
nameList[count] = name;
saleList[count] = String.valueOf(sale);
count++;
for (int i = 0; i < nameList.length; i++) {
if (nameList[i] != null) {
System.out.println(nameList[i] + " " + saleList[i]);
}
}
data.close();
}
} catch (IOException e) {
}}
Try the code below.
There were 2 issues in the code I could see.
a) You did not declare the variable count
b) You were printing while reading the data, and that is not desirable.
public static void readData(){
File infile = new File("D:\\itemData.txt");
String itemName = new String();
String[] nameList = new String[100];
String[] saleList = new String[100];
int sale;
int count = 0;
try {
Scanner data = new Scanner(infile);
while (data.hasNext()) {
itemName = data.next();
sale = data.nextInt();
nameList[count] = name;
saleList[count] = String.valueOf(sale);
count++;
data.close();
}
} catch (SIOException e) {
}
for (int i = 0; i < nameList.length; i++) {
if (nameList[i] != null) {
System.out.println(nameList[i] + " " + saleList[i]);
}
}
}
Also consider implementing something like this to keep track of maxes and mins for you:
package com.example.demo;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.collections4.map.HashedMap;
public class Inventory {
private Map<String, AtomicInteger> totals = new HashedMap<>();
private Map<String, AtomicInteger> maxes = new HashedMap<>();
private Map<String, AtomicInteger> mins = new HashedMap<>();
public void add(String name, int number) {
getOrCreateFromMap(totals, name, 0).addAndGet(number);
getOrCreateFromMap(maxes, name, Integer.MIN_VALUE).getAndUpdate(present -> (present < number) ? number : present);
getOrCreateFromMap(mins, name, Integer.MAX_VALUE).getAndUpdate(present -> (number < present) ? number : present);
}
private AtomicInteger getOrCreateFromMap(Map<String, AtomicInteger> map, String name, int initialValue) {
return map.computeIfAbsent(name, x -> new AtomicInteger(initialValue));
}
public int getTotal(String name) {
return getFromMap(totals, name);
}
public int getMax(String name) {
return getFromMap(maxes, name);
}
public int getMin(String name) {
return getFromMap(mins, name);
}
private int getFromMap(Map<String, AtomicInteger> map, String key) {
return map.computeIfAbsent(key, x -> new AtomicInteger())
.get();
}
public static void main(String[] args) {
Inventory i = new Inventory();
i.add("paper", 50);
i.add("paper", 150);
System.out.println(i.getTotal("paper"));
System.out.println(i.getMax("paper"));
System.out.println(i.getMin("paper"));
}
}
Here is a working example, for the mentioned problem statement -
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.stream.Collectors;
public class ReadAndSumFileData {
public static void main(String... arguments) throws IOException {
String filename = "C:/temp/SalesData.txt";
readData(filename);
}
private static void readData(String filename) throws IOException {
Map<String, Integer> map = Files.lines(Paths.get(filename))
.map(s -> s.split("\\s+"))
.collect(Collectors.groupingBy(a -> a[0], Collectors.summingInt(a -> Integer.parseInt(a[1]))));
map.entrySet().stream().forEach(e-> System.out.println(e));
}
}

InputMismatchException error with Java Scanner when using Eclipse on Mac but not on Win10

I'm getting a behaviour that I can't understand. The code works perfectly on Win10 but throws an InputMismatchException error on MacOS. It breaks when trying to call nextDouble() or nextInt().
The call is made from this method:
public void readVehicleData()
{
Frame frame = null;
FileDialog fileBox = new FileDialog(frame, "Open", FileDialog.LOAD);
fileBox.setDirectory(".");
fileBox.setVisible(true);
String fileName = fileBox.getDirectory()+fileBox.getFile();
try
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
while(scanner.hasNextLine())
{
String lineOfText = scanner.nextLine().trim();
if (!lineOfText.startsWith("//") && !lineOfText.isEmpty() && !lineOfText.startsWith("["))
{
Scanner strScanner = new Scanner(lineOfText).useDelimiter("\\s*[,\n]\\s*");
Vehicle vehicle = new Vehicle();
if(strScanner.hasNext())
{
vehicle.readData(strScanner);
vehicleList.add(vehicle);
strScanner.nextLine();
}
strScanner.close();
}
}
if(scanner.hasNextLine())
{
scanner.nextLine();
}
scanner.close();
}
catch(FileNotFoundException ex)
{
System.err.println(ex.getMessage());
System.err.println(ex.getCause());
ex.printStackTrace();
System.err.println("File " + fileName + " not found");
fileName = null;
}
The error occurs when reading "vehicle.readData(strScanner)", which looks like this:
public void readData(Scanner strScanner)
{
group = strScanner.next();
vehID = strScanner.next();
regNo = strScanner.next();
make = strScanner.next();
model = strScanner.next();
String strAirCon = strScanner.next();
airCon = strAirCon.equalsIgnoreCase("Yes") == true ? true : false;
// It throws an InputMismatchException error here
engineSize = strScanner.nextDouble();
fuelType = strScanner.next();
gearbox = strScanner.next();
transmission = strScanner.next();
// It also throws an InputMismatchException error here
// if the previous variables are commented
mileage = strScanner.nextInt();
dateFirstRegistered = strScanner.next();
}
These are the errors I get:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at vehicleproject.Vehicle.readData(Vehicle.java:121)
at vehicleproject.ReservationSystem.readVehicleData(ReservationSystem.java:65)
at vehicleproject.Main.main(Main.java:10)
I've obviously done my research but can't find any solution for that. It works without any issue on Win10 but not on MacOS.
Has anyone experience the same type of error on MacOS?
This is an example of the data I need to read:
[Car data]
// data is Group, VehID, RegNo, Make, Model, AirCon or Climate Control, Engine Size (litres), Fuel type, Gearbox, Transmission, Mileage, Date first registered, Body type, Number of doors, Number of seats
AA, TF-63403, MJ09TFE, Fiat, Panda Active Eco, No, 1.1, Unleaded, five-speed manual, FWD, 13584, 29-07-2009, Hatchback, 5, 5
A, TF-61273, MJ09TFD, Fiat, Grande Punto Active, No, 1.4, Unleaded, five-speed manual, FWD, 14278, 12-05-2009, Hatchback, 3, 5
This is one of the classes:
import java.util.*;
import java.awt.*;
import java.io.*;
public class Vehicle
{
private String group, vehID, regNo, make;
private String model, fuelType, gearbox, transmission, dateFirstRegistered;
private boolean airCon;
private double engineSize;
private int mileage;
public Vehicle()
{
group = null;
vehID = null;
regNo = null;
make = null;
model = null;
airCon = false;
engineSize = 0.0;
fuelType = null;
gearbox = null;
transmission = null;
mileage = 0;
dateFirstRegistered = null;
}
public String getGroup()
{
return group;
}
public void setGroup(String newGroup)
{
group = newGroup;
}
public String getVehicleID()
{
return vehID;
}
public void setVehicleID(String newVehID)
{
vehID = newVehID;
}
public String getRegistrationNo()
{
return regNo;
}
public void setRegistrationNo(String newRegNo)
{
regNo = newRegNo;
}
public String getMake()
{
return make;
}
public void setMake(String newMake)
{
make = newMake;
}
public String getModel()
{
return model;
}
public void setModel(String newModel)
{
model = newModel;
}
public boolean getAirCon()
{
return airCon;
}
private String checkAirCon()
{
String output;
return output = getAirCon() == true ? "Yes" : "No";
}
public void printDetails()
{
System.out.println(make + " " + model + " Group: " + group + " Vehicle Id: " + vehID);
System.out.println("Air conditioning / Climate control: " + checkAirCon());
System.out.println("Engine Size: " + engineSize + " Fuel: " + fuelType);
System.out.println("Gearbox: " + gearbox + " Transmission: " + transmission);
System.out.println("Mileage: " + mileage + " Date first registered: " + dateFirstRegistered);
System.out.println();
}
public void readData(Scanner strScanner)
{
group = strScanner.next();
vehID = strScanner.next();
regNo = strScanner.next();
make = strScanner.next();
model = strScanner.next();
//System.out.println(model);
String strAirCon = strScanner.next();
airCon = strAirCon.equalsIgnoreCase("Yes") == true ? true : false;
engineSize = strScanner.nextDouble();
//System.out.println(engineSize);
fuelType = strScanner.next();
gearbox = strScanner.next();
transmission = strScanner.next();
mileage = strScanner.nextInt();
//System.out.println(mileage);
dateFirstRegistered = strScanner.next();
}
}

Using array as key for hashmap java

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

Handling a .data file with uneven whitespaces delimited and populate to an bean object using java program

How to handle file data as shown below, which is delimited by uneven whitespaces, where if tokenizer is used based on space, it'll give tokens which cannot be assigned to java bean fields directly.
Below is the content Data of cheapdata4.data:
(TX 260816.<
0954F2003EGGPLEIBLNX37PU ZC550 Z <CA C A L L8 STAF P18 UL15 KIDL
0001F0148BIKFEDDSGWI2797 ZA319 Z <CATGWI2 C M V104 GMH4 GMH UL60 EDDS
4893F1416EGPGEGHFGJOID ZSR20 Z <AAEGPGD C A LT TLA DCS L612 N859 Q41
7945F1400EGSHEGCCLOG63JF ZD328 Z <(A C A R L OTBE Y70 EGCC
7946F1647EGSHEGGWAZE01F ZE50P Z <(A C A R LT MAM1 LAPR ABBO BKY2
7947F1701EGSHEGCCLOG63JF ZD328 Z <(A C A R L / MAM0 OTBE POL ROSU
4368F1657ESSBEGGWBLJ59BF ZC56X Z <RAUBLJ5 A LT UN86 UP7 UP25 EGGW
4369F1728ESSBEGCCETI226L MLJ45 012<RAUETI2 A L UL97 Y70 EGCC
4370F0551LHBPEGGWWZZ196 ZA321 Z <RAUWZZ1 A MT UL60 UY6 UM20 EGGW
7950END 260816.<
package com.msa.parser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.msa.bean.CheapData;
public class FinalParser {
public static void main(String[] args) {
BufferedReader reader;
try {
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(
new FileReader(
"C:\\Users\\Desktop\\assignment\\cheapdata4.data"));
System.out.println("Reading file...");
String line = reader.readLine();
line = line.replaceAll("\\s{2,}", " ");
String[] toks = line.replace(" ", ",").trim().split(",");
line = line.replaceAll("\\s{2,}", " ");
String[] headerTokens = line.split(" +");
String fileStartDate = headerTokens[1].substring(0, 6);
List<String> cheapDataContent = new ArrayList<>();
String[] lineTokens = { "" };
CheapData cheapFileDets = null;
List<CheapData> cheapDataList = new ArrayList<>();
while (line != null) {
line = reader.readLine();
line = line.replaceAll("\\s{2,4}", " ");
// line = line.replaceAll("\\s{2}", " NA ");
// line = line.replaceAll(" ",", ");
// line = line.replaceAll("\\,{2}", "");
lineTokens = line.split(" +");
int len = lineTokens.length;
// String fileEndDate ="";
if (len == 2) {
String fileEndDate = lineTokens[1].substring(0, 6);
if (fileStartDate.equals(fileEndDate)) {
break;
} else {
System.out.println("Date mismatch...");
}
}
if (len >= 6) {
cheapFileDets = new CheapData();
String lineNum = lineTokens[0].substring(0, 4);
cheapFileDets.setLineNum(lineNum);
String cheapReference = lineTokens[0].substring(4);
cheapFileDets.setCheapReference(cheapReference);
cheapFileDets.setDate(fileStartDate);
cheapFileDets.setAircraftCode(lineTokens[1]);
cheapFileDets.setIdentifierCode(lineTokens[2]);
cheapFileDets.setLicenseCode(lineTokens[3]);
if (lineTokens[4].equals("C"))
cheapFileDets.setCodeOne(lineTokens[4]);
else
cheapFileDets.setCodeOne(null);
if (lineTokens[5].equals("A"))
cheapFileDets.setCodeTwo(lineTokens[5]);
else
cheapFileDets.setCodeTwo(null);
if (lineTokens[6].equals("R"))
cheapFileDets.setCodeThree(lineTokens[6]);
else
cheapFileDets.setCodeThree(null);
} else {
if (len == 7)
cheapFileDets.setIdCode(lineTokens[7]);
else
cheapFileDets.setIdCode(null);
}
List<String> miscList = new ArrayList<>();
for (int i = 7; i < len - 1; i++) {
miscList.add(lineTokens[i]);
}
StringBuilder miscAll = new StringBuilder("");
for (String miscs : miscList) {
miscAll.append(miscs + " ");
}
cheapFileDets.setMiscAll(miscAll.toString());
cheapDataList.add(cheapFileDets);
}
System.out.println("File content" + sb.toString());
System.out.println("file date is: " + fileStartDate);
System.out.println("*************");
/*
* for (String strToks : lineTokens) { System.out.println(strToks);
* }
*/
// System.out.println(cheapDataList);
Iterator<CheapData> itrCheapData = cheapDataList.listIterator();
while (itrCheapData.hasNext()) {
System.out.println(itrCheapData.next());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
package com.msa.bean;
public class CheapData {
private String lineNum;
private String date;
private String cheapReference;
private String aircraftCode;
private String identifierCode;
private String licenseCode;
private String codeOne;
private String codeTwo;
private String codeThree;
private String idCode;
private String miscAll;
public String getLineNum() {
return lineNum;
}
public void setLineNum(String lineNum) {
this.lineNum = lineNum;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCheapReference() {
return cheapReference;
}
public void setCheapReference(String cheapReference) {
this.cheapReference = cheapReference;
}
public String getAircraftCode() {
return aircraftCode;
}
public void setAircraftCode(String aircraftCode) {
this.aircraftCode = aircraftCode;
}
public String getIdentifierCode() {
return identifierCode;
}
public void setIdentifierCode(String identifierCode) {
this.identifierCode = identifierCode;
}
public String getLicenseCode() {
return licenseCode;
}
public void setLicenseCode(String licenseCode) {
this.licenseCode = licenseCode;
}
public String getCodeOne() {
return codeOne;
}
public void setCodeOne(String lineTokens) {
this.codeOne = lineTokens;
}
public String getCodeTwo() {
return codeTwo;
}
public void setCodeTwo(String lineTokens) {
this.codeTwo = lineTokens;
}
public String getCodeThree() {
return codeThree;
}
public void setCodeThree(String codeThree) {
this.codeThree = codeThree;
}
public String getIdCode() {
return idCode;
}
public void setIdCode(String idCode) {
this.idCode = idCode;
}
public String getMiscAll() {
return miscAll;
}
public void setMiscAll(String miscAll) {
this.miscAll = miscAll;
}
public CheapData(String lineNum, String date, String cheapReference,
String aircraftCode, String identifierCode, String licenseCode,
String codeOne, String codeTwo, String codeThree, String idCode,
String miscAll) {
super();
this.lineNum = lineNum;
this.date = date;
this.cheapReference = cheapReference;
this.aircraftCode = aircraftCode;
this.identifierCode = identifierCode;
this.licenseCode = licenseCode;
this.codeOne = codeOne;
this.codeTwo = codeTwo;
this.codeThree = codeThree;
this.idCode = idCode;
this.miscAll = miscAll;
}
#Override
public String toString() {
return "CheapData [lineNum=" + lineNum + ", date=" + date
+ ", cheapReference=" + cheapReference + ", aircraftCode="
+ aircraftCode + ", identifierCode=" + identifierCode
+ ", licenseCode=" + licenseCode + ", codeOne=" + codeOne
+ ", codeTwo=" + codeTwo + ", codeThree=" + codeThree
+ ", idCode=" + idCode + ", miscAll=" + miscAll + "]";
}
public CheapData() {
super();
}
}
Please can anyone help me out in this regard. I want to parse above file and populate each columns from that to an object using setters in java.
Please do suggest me how to achieve this and kindly let me know if my query not clear.

Parsing files in java/android

I have a text file that has is set out like the following
Title - Welcome to the Dibb
Date - 13/03/11
Information - Hello and welcome to our website.
Title - Welcome to student room
Date - 06/05/11
Information - Hello and welcome to the student room. We are a online forum that allows previous and current students to ask questions.
I need to parse this text file and save things like the title line, date line and the rest will be saved as information. I know how to read the file and save the full file as a string but I am stuck on getting the select information.
CODE
This is the code I have used to read the text file
helloTxt.setText(readTxt());
}
private String readTxt() {
InputStream inputStream = getResources().openRawResource(R.raw.pages);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1) {
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = byteArrayOutputStream.toString();
return str;
}
Read file line by line
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
br.close();
If you can guarantee that every line has as maximum one - then you can use following pattern.
String[] tokens = line.split("\s-\s");
For this line
Title - Welcome to the Dibb
It would give you
tokens[0] = "Title";
tokens[1] = "Welcome to the Dibb";
I try to write some classes which can help you to approach your issue
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class Test4 {
private List<Information> parser(String data) {
List<Information> informations = new ArrayList<Information>();
String blocks[] = data.split("\n\r");
for(String block : blocks) {
String[] lines = block.split("\n");
Information information = new Information();
information.setTitle((lines[0].split("-"))[1].trim());
information.setDate((lines[1].split("-"))[1].trim());
information.setInfo((lines[2].split("-"))[1].trim());
informations.add(information);
}
return informations;
}
private void runner() throws IOException {
InputStream inputStream = getClass().getResourceAsStream("input.txt");
String input = "";
int cc;
while((cc = inputStream.read()) != -1) {
input += (char) cc;
}
List<Information> informations = parser(input);
for(Information information : informations) {
System.out.println(information);
}
}
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
Test4 test4 = new Test4();
test4.runner();
}
class Information {
private String title;
private String date;
private String info;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
#Override
public String toString() {
return "Information [" + (title != null ? "title=" + title + ", " : "")
+ (date != null ? "date=" + date + ", " : "") + (info != null ? "info=" + info : "") + "]";
}
}
}

Categories