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);
}
}
Related
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!
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);
}
I have got a question about a code I have written
package salescities;
import java.io.File;
import java.util.Scanner;
public class SalesCities {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double totalSales = 0;
int count = 0;
int missingCount = 0;
String line;
File file;
Scanner input;
try {
file = new File("sales.txt");
input = new Scanner(file);
input.useDelimiter(":");
while (input.hasNextLine()) {
input.next();
line = input.nextLine();
try{
totalSales += Double.parseDouble(line);
count++;
}
catch(IllegalArgumentException e){
missingCount++;
}
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(totalSales + " " +missingCount);
}
}
And the file im trying to read is like this
New York: 23.5678
New Jersey: no reports
Rio de Janeiro: 12.3654
When i run the program however it prints out 0.0 3 like all is missing.
The problem is when i run the debugger to see whats happening to line so parseDouble isn't functioning and i saw that line is a string that has this
: 23.5678
and I don't understand why if I'm using ":" as delimeter. I expected only the number without the colon. Can someone answer me?
ps: this is an exercise from a book that's quite simple but the book uses a class TextIO that is implemented by them. just wanted to try scanner instead of their code.
Scanner#nextLine grabs the rest of the line, regardless of the delimiter.
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. — Scanner#nextLine
I have two classes, one with instance variables and the other will read a file. The file with one main loop will store an array of workers. I don't know when the getMethods should be placed.
the file has looks a bit like this:
Joames peter 5 15.00
Laura Kelly 30 12.00
Tim McAdam 18 15.00
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class PayRoll {
private static Scanner kbd;
public static void main(String[] args) {
final int NUMBER_OF_WORKERS = 15;
final String INPUT_FILE = "data.txt";
Worker[] worker_ar = new Worker[NUMBER_OF_WORKERS];
try{
kbd = new Scanner(new File(INPUT_FILE));
}
catch(FileNotFoundException e){
System.err.println("File Not Found!");
}
String line = null;
int i = 0 ;
while((kbd.hasNextLine()) && (i < worker_ar.length))
{
// these are the variables I have in the other class. I need these so I can
// later reverse the file data and comute total pay and average pay.
line = kbd.nextLine();
worker_ar[i] = (getfName(), getlName(), getHours(), gethrly_pay());
i++;
}
kbd.close();
}
// I will put two methods here to make the file reverse
}
Use StringTokenizer with space separator.
Nitpick: Use Employee instead of Worker. It's has more sense, and Worker used in Java for something else.
In this program I am just getting input from a file and trying to get the boys name and the girls name out of it, and also put them in separate files. I have done everything just as the book has stated. And I've also searched everywhere online for help with this but cant seem to find anyone with the same problem. Ive seen problems where its not -1 but a positive number because they went to far out of the string calling a substring over the strings length. But cant seem to figure out this giving me -1 since i's value is 1.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
public class Homework_11_1 {
public static void main(String[] args)throws FileNotFoundException
{
File inputFile = new File("babynames.txt");
Scanner in = new Scanner(inputFile);
PrintWriter outBoys = new PrintWriter("boys.txt");
PrintWriter outGirls = new PrintWriter("girls.txt");
while (in.hasNextLine()){
String line = in.nextLine();
int i = 0;
int b = 0;
int g = 0;
while(!Character.isWhitespace(line.charAt(i))){ i++; }
while(Character.isLetter(line.charAt(b))){ b++; }
while(Character.isLetter(line.charAt(g))){ g++; }
String rank = line.substring(i);
String boysNames = line.substring(i, b);
String girlsNames = line.substring(b, g);
outBoys.println(boysNames);
outGirls.println(girlsNames);
}
in.close();
outBoys.close();
outGirls.close();
System.out.println("Done");
}
}
Here is the txt file
1 Jacob Sophia
2 Mason Emma
3 Ethan Isabella
4 Noah Olivia
5 William Ava
6 Liam Emily
7 Jayden Abigail
8 Michael Mia
9 Alexander Madison
10 Aiden Elizabeth
I would have written it an other way, using split.
public static void main(String[] args)throws FileNotFoundException
{
File inputFile = new File("babynames.txt");
Scanner in = new Scanner(inputFile);
PrintWriter outBoys = new PrintWriter("boys.txt");
PrintWriter outGirls = new PrintWriter("girls.txt");
while (in.hasNextLine()){
String line = in.nextLine();
String[] names = line.split(" "); // wile give you [nbr][boyName][GirlName]
String boysNames = names[1];
String girlsNames = names[2];
outBoys.println(boysNames);
outGirls.println(girlsNames);
}
in.close();
outBoys.close();
outGirls.close();
System.out.println("Done");
}
Rather than fuss with loops and substring(), I'd just use String.split(" "). Of course, the assignment may not permit you to do this.
But anyway, without giving you the answer to the assignment, I can tell you that your logic is wrong. Walk through it and find out why. If you try running this code on just the first line of the input file, you'll get these values: i=1, b=0, and g=0. Calling line.substring(1,0) is obviously not going to work.