I am trying to write a program for class that reads a list of hours worked annually from a .txt file, assigns/reads (A little fuzzy on the proper terminology :)) them into an array, and then calculates overages and prints them.
When I run, console output is as follows:
Employee 1 worked 1600 hours, an under-run of 160 or 0%
Employee 3 worked 1680 hours, an under-run of 80 or 0%
Why are the percentages zero?
import java.io.*;
import javax.swing.*;
class Calculator
{
public static void main(String args[])
{
try{
String filePathString=JOptionPane.showInputDialog(null,"What is the file path?");
FileInputStream fstream = new FileInputStream("C:\\hello.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int counter = 0;
long[] Array = new long[5];
//Read File Line By Line
while (counter <= 4)
{
strLine = br.readLine();
Array[counter] = Long.parseLong(strLine);
OverageUnderage(Array[counter], counter);
counter = counter + 1;
}
//Close the input stream
in.close();
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
public static long OverageUnderage(long hours, long counter)
{
long overageAmount = 0;
long overagePercent = 0;
if (hours < 1760)
{
overageAmount = 1760 - hours;
overagePercent = ((overageAmount/1760)*100);
System.out.println("Employee "+counter+" worked "+hours+" hours, an under-run of "+overageAmount+" or "+overagePercent+"%");
}
return counter;
}
}
The number
( overageAmount / 1760 )is being treated as a long, not a double, which you’ll need. Try:using the
.0on 1760 will have it treated as a decmial value. This will prevent the rounding to 0 issue you were seeing, and allow the calculation to have decimals for the rest of the calculations, providing you with your desired result.