Adding values from 2 different files - java

In my program I scan 2 files, the 1st file I get the hours and the payRate to calculate each individual employees base pay, the 2nd file gets the sales of each employee to calculate the commissions for that week.
Then I combine the results in one file, but I need to add the commission and the base pay for each employee to get the weekly grosspay for each employee. I'm at a lost here, I want to add each individual base pay with their respective commissions to get the weekly grosspay, also, I added social security number, Is there a way that I could do this with separate files or the same file scanning for numbers with the same identifier (in this case the same social security number) and add the corresponding values?Two files (1) Salary_Hours (2) Sales
import java.util.*;
import java.io.*;
public class Payroll_Sales {
private static Scanner kb = new Scanner(System.in);
public static void main(String[] args) throws IOException {
File fileSalary = new File ("Salary.txt");
File salaryFile = new File ("NewPrint.txt");
PrintWriter salaryPrint = new PrintWriter (salaryFile);
salaryPrint = getSalary (fileSalary, salaryFile);
File fileSales = new File ("Sales.txt");
FileWriter salesFile = new FileWriter ("NewPrint.txt", true);
PrintWriter salesPrint = new PrintWriter (salesFile);
salesPrint = getSales (fileSales, salesFile);
}
private static PrintWriter getSales(File fileSales, FileWriter salesFile) throws FileNotFoundException {
PrintWriter salesPrint = new PrintWriter (salesFile);
Scanner scan = new Scanner (fileSales);
String ssn;
double sales = 0, commission=0, salesCommission=0;
while (scan.hasNext()) {
ssn = scan.next();
sales = scan.nextDouble();
if (sales >= 10000) {
commission = .15;
}
else if (sales >= 7500) {
commission = .10;
}
else if (sales >= 4500) {
commission = .07;
}
else {
commission = .05;
}
salesCommission = commission*sales;
salesPrint.printf("%11s $ %,3.2f \n", ssn, salesCommission);
System.out.printf("%11s $ %,3.2f \n", ssn, salesCommission);
}
salesPrint.close();
return salesPrint;
}
private static PrintWriter getSalary(File fileSalary, File salaryFile) throws FileNotFoundException {
PrintWriter salaryPrint = new PrintWriter (salaryFile);
Scanner scan = new Scanner (fileSalary);
String ssn;
double salary = 0, hours=0, payRate=0;
while (scan.hasNext()) {
ssn = scan.next();
payRate = scan.nextDouble();
hours = scan.nextDouble();
salary = payRate * hours;
salaryPrint.printf("%11s $ %,3.2f \n", ssn, salary);
System.out.printf("%11s $ %,3.2f \n", ssn, salary);
}
System.out.println();
salaryPrint.println();
salaryPrint.close();
return salaryPrint;
}
}
CombineFile_Salary and SalesCommissions

In my experience, I tend to divide file or IO work into two steps.
1) Parse the input into a model
This could be an class representing your application with additional classes for different data types (Employee has a sales num, payrate, num hours etc)
2) Now that you have your model, introduce your business logic since you should have all the information you need since once parsing is done.
Note, depending on the size of your input, the amount of memory needed will scale proportionately so if the size of these files is very large, I recommend you introduce a database or something as that will be a lot easier to manage (I don't expect this will be necessary based on your initial code)
The pseduo code would look something like this
public static <ModelClass> parseInput(file1, file2){
//Read through the files and instantiate your model data
//This should cover any information you need in your business logic
//(Meaning you should be able to close the files and not open them again
}
public <ModelClass> calculatePay(<ModelClass> model){
//Use your data structure to compute what you want to compute
//Return modified instance of the model
}
The reason I suggest this is because I have spent too much time in the past trying to do it all at once (parsing data from a file and computing logic). It's not always the right answer, but that's what refactoring is for!

Related

Program freezes during run at While loop

The program I am writing needs to read 4 lines of data from a text file containing an ID, Name, Level, and Salary for an employee. It then needs to create a formatted email address and print all of this to standard output. The text file can contain an unknown number of employees, so a while loop must be used with the hasNext() method to confirm there is more data to read.
My program freezes (using Dr. Java) as soon as the while loop begins, and I cant figure out why.
Here is my code so far
public static void main(String[] args) throws IOException {
File file = new File("employeeInput.txt");
if (file.exists()) { //check if file exists
Scanner inputFile = new Scanner(file); //opens file
String companyName = inputFile.nextLine();
System.out.println(companyName);
System.out.println();
System.out.println("----------------------------");
while (inputFile.hasNext()); {
String studentID = inputFile.nextLine();
System.out.println(studentID);
String studentName = inputFile.nextLine();
System.out.println(studentName);
String employeeLevel = inputFile.nextLine();
System.out.println(employeeLevel);
double salary = inputFile.nextDouble();
System.out.println(salary);
}
inputFile.close();
}
else {
System.out.println("The file employeeInput.txt does not exist");
}
}
}
I understand this code is not complete and does everything the program needs to, but I do not get why it's freezing at the while loop..
Any help or advice would be appreciated. This is my first class ever in programming language, so go easy on me :)

Java - unable to change data type from an import file

I am trying to convert the import file String data type to Double and do the calculations, but some errors found. Any mistakes when making an assumption?
import java.io.*;
import java.util.*;
import java.lang.*;
public class Q4
{
public static void main (String [] args) throws IOException, NumberFormatException
{
File file = new File("SalesData.txt");
Scanner inputFile = new Scanner (file);
while (inputFile.hasNext())
{
String weekly_Sale = inputFile.nextLine();
String sale = weekly_Sale;
String list = sale;
Double value = Double.parseDouble(list);
Double[]data = value.split(",");
System.out.println(data);
}
inputFile.close();
}
}
The file SalesData.txt contains the dollar amount of sales that a retail store made each day for a number of weeks. Each line in the file contains seven numbers, which are the daily sales for one week. The numbers are separated by a comma. The following is an example from the file:
2541.36,2965.88,1965.32,1845.23,7021.11,9652.74,1469.36
Write a program that opens the file and processes its contents. The program should display the following:
• The total sales for each week
• The average daily sales for each week
• The total sales for all the weeks
• The average weekly sales
• The week number that had the highest amount of sales
• The week number that had the lowest amount of sales
Various things to point out:
As I commented before, Double doesn't have a split method and you can't directly parse to double a String like 2541.36,2965.88,1965.32...
It's better to use BufferedReader than Scanner to read a file because is
a bit faster
You can use the try-with-resources statement to automatically close the io resources.
Your code can be shortened like this:
try (BufferedReader br = new BufferedReader(new FileReader("SalesData.txt"))){
String currentLine;
// read each line until the end of the file
while ((currentLine = br.readLine()) != null){
// split each token to a double-parseable string value, then parse it to a double and finally
// collect those values into an array of doubles
double[] data = Arrays.stream(currentLine.split(",")).mapToDouble(Double::parseDouble).toArray();
System.out.println(Arrays.toString(data));
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
For this I'm using Java 8 Stream API.
Double value = Double.parseDouble(list);
Double[]data = value.split(",");
The order of your operations is incorrect. At first you need to split the line into individual string values and then parse them to double.
Try something like this
String[] data = value.split(",");
for (String item : data) {
Double result = Double.parseDouble(item)
// Do Stuff
}
Try this
String inputFile = new Scanner(new File("SalesData.txt"))
.useDelimiter("\\A").next();
String[] s = inputFile.split(",");
double[] dValue = new double[s.length];
for (int i = 0; i < s.length; i++) {
dValue[i] = Double.parseDouble(s[i]);
}
for (double d : dValue) {
System.out.println(d);
}

How to read data from file to create objects?

I'm struggling to figure out how to read the data from a file we've been given and use that to create an instance of an object. We are given a txt file of customer data for a store. It is in the following format:
123.64382392 12 1.1234123419
Each line of the file is like this. The first column is Arrival time, the second is number of items, and the third is the time it takes the customer to find one item. There are about 100 customers in this file and I'm not sure how to read from the file to create all the instances necessary.
public static void loadCustomers(){
File file = new File("origCustomerArrivals.txt");
try{
Scanner input = new Scanner(file);
while (input.hasNextLine())
{
double arrivalTime = input.nextDouble();
int numItems = input.nextInt();
double selectionTime= input.nextDouble();
Customer newCustomer = new Customer(arrivalTime, numItems,selectionTime);
input.nextLine();
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("file not opened");
}
}
}
Try this:
public static void loadCustomers(){
File file = new File("origCustomerArrivals.txt");
try{
List<Customer> list = new ArrayList<Customer>();
Scanner input = new Scanner(file);
while (input.hasNextLine())
{
String[] values = scan.nextLine().split("\\s+");
arrivalTime = Double.parseDouble(values[0]);
numItems = Integer.parseInt(values[1]);
selectionTime = Double.parseDouble(values[2]);
Customer newCustomer = new Customer(arrivalTime, numItems,selectionTime);
list.add(newCustomer);
input.nextLine();
}
input.close();
}
catch(FileNotFoundException e){
System.out.println("file not opened");
}
}
}
Could you elaborate on what part of your code isn't working? I tested it myself (printed out the values instead of creating a new Customer object), and it works fine. Except "input.nextLine();" in the while loop is not necessary. It will already jump to the next line, and once you reach the end of your file that will likely cause an error to be thrown.
Also, once you create the object instance, I assume you'll want to save it to a list of the objects. You can do this by creating an ArrayList of object Customer outside the loop:
ArrayList<Customer> Customers = new ArrayList<Customer>();
Then as each instance is created in the loop, add it to this ArrayList:
Customers.add(newCustomer);

Java text file input

i am currently doing a small task in java which i am very new to so please excuse any silly mistakes i have made. Basically i am trying to take 2 values from a text document, import them into my java document and then multiply them together. These 2 numbers are meant to represent the hourly pay and amount of hours worked, then the output is the total amount the member of staff has earned. This what i have so far ...
import java.util.*;
import java.io.*;
public class WorkProject
{
Scanner inFile = new Scanner(new FileReader("staffnumbers.txt"));
double Hours;
double Pay;
Hours = inFile.nextDouble();
Pay = inFile.nextDouble();
double earned = Length * Width;
System.out.println(earned);
}
What i have so far is basically me trying to get the .txt document into my java file. I'm not sure if this is right and then i'm not sure where to go to get the values to multiply and have it outputted. I understand what i have so far is probably just the very start of what i need but any help will be massively appreciated as i am keen to learn. Thanks so much .... Hannah
I don't know what Amount earned is. So my guess is you need to change the last line to
double amountEarned = Hours * Pay; //this multiplies the values
System.out.println(amountEarned); //this outputs the value to the console
EDIT:
Putting code inside a main method:
public class WorkProject {
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new FileReader("C:\\staffnumbers.txt"));
double Hours;
double Pay;
Hours = inFile.nextDouble();
Pay = inFile.nextDouble();
double amountEarned = Hours * Pay;
System.out.println(amountEarned);
}
}
// Matt Stillwell
// April 12th 2016
// File must be placed in root of the project folder for this example
import java.io.File;
import java.util.Scanner;
public class Input
{
public static void main(String[] args)
{
// declarations
Scanner ifsInput;
String sFile;
// initializations
ifsInput = null;
sFile = "";
// attempts to create scanner for file
try
{
ifsInput = new Scanner(new File("document.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("File Doesnt Exist");
return;
}
// goes line by line and concatenates the elements of the file into a string
while(ifsInput.hasNextLine())
sFile = sFile + ifsInput.nextLine() + "\n";
// prints to console
System.out.println(sFile);
}
}

How to edit a txt file using PrintWriter?

I have the following java file that stores student data (a student number and their surname) in a txt file:
import java.util.*;
import java.io.*;
public class Students {
static Student[] studentArray = new Student[100];
static int currentStudents = 0;
Scanner console = new Scanner(System.in);
File log = new File("log.txt");
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(log, true)));
Scanner input = new Scanner(log);
public static void main(String[] args) {
String logNo;
String logSurname;
if(!(input.hasNextLine())) {
System.out.println("No student data has been loaded.")
}
while(input.hasNextLine()) {
logNo = input.next();
logSurname = input.next();
addStudent(logNo, logSurname);
input.nextLine();
}
String number;
String surname;
System.out.println("Please input details:");
System.out.printf("\n");
System.out.println("Student number: ");
number = console.nextLine();
System.out.println("Student surname: ");
surname = console.nextLine();
output.println(number+"\t"+surname);
addStudent(number, surname);
editSurname();
output.close();
}
public static void addStudent(String number, String surname) {
studentArray[currentStudents] = new Student(number, surname);
}
public static void editSurname() {
String newSurname;
System.out.println("Please input student number:");
// find student with inputted student number
System.out.println("Please enter new surname");
// set surname to another using Student method
}
}
Upon opening, the code reads in any text in the .txt file and constructs Student objects as required, so that the state of the system persists everytime the code runs.
However, I'm struggling to find a way to edit the .txt file using PrintWriter when I call my editSurname() function. How would I go about isolating the student with a specific student number and then edit the required field?
Use a csv file instead of a txt file. Use OpenCSV to process the records.
OR
Have your txt file 1 record per line.
Separate each field by separator.
Create another temporary text file in memory.
Modify the records and save the records in the temporary file.
Delete the original file.
Rename the temporary file with original file name.
For editing your student record, you need to first read all the records in memory.
Create an array of student objects to hold all the records. Perform a binary search on the
objects and modify them.
Why should not use Database concept, It is easily done with Database

Categories