In: Computer Science
how do you read in a file in JAVA
Assume there is a file called "mydata". each line of the file contains two data items: hours and rate. hours is the represented by the number of hours the worker worked and rate is represented as hourly rate of pay. The first item of data is count indicating how many lines of data are to follow.
Methods
pay- accepts the number of hours worked and the rate of pay. returns the dollor and cents amount of the amount earned as follows. workers who worked 40 hours or less are paid at their regular rate and workers who worked more then 40 hours are paid their regular rate for the first 40 hours then 100% of their rate for hours in excess of 40.
Example
worker is paid at at rate of $11.00/hours. if worker works for 25 hours he will be paid 25*11=275. if work works for 60 hours he will be paid (40*11)+(20*10)=640
main method
read the count
for each line of data read the number of hours worked and the employee rate
compute the gross pay
data file
4
5 25.00
40 50.00
30 40.00
10 15.00
Implemented code as per the requirement, but small confusion with the condition for extra hours worked. 100% of their rate implies that they should be payed double the amount for the extra hours. Implemented logic as I uderstood your words but not according to the example you gave. If it is wrong please comment so that I can modify the answer.
Code:
=====
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Payroll {
static File file;
static Scanner sc;
public static void main(String[] args) throws FileNotFoundException {
sc = new Scanner(System.in);
System.out.print("Enter number of records you want to process: ");
int i = Integer.parseInt(sc.nextLine());
file = new File("mydata");
sc = new Scanner(file);
int j=0;
String str = "";
while(j
j++;
str = sc.nextLine();
System.out.println("Number of hours employee worked: "+Integer.parseInt(str.split(" ")[0])+" and payment is: "+pay(Integer.parseInt(str.split(" ")[0]),Float.parseFloat(str.split(" ")[1])));
}
}
private static double pay(int hours, double rate) {
if(hours>40){
return (40*rate)+((hours-40)*rate*2);
}
else{
return hours*rate;
}
}
}
Output screen: