This is the question of the program:
Write a Java Application program that will determine the gross pay for each of several employees (Use either ‘while’, ‘for’, or ‘do/while’ loop to input several employees). The company pays "straight time" for the first 40 hours worked by each employee and pays "time-and-a-half" for all hours worked in excess of 40 hours. Your program should ask the user to input the hours worked and the rate per hour.
Put all output in one window. Format your gross pay in two decimal places.
This is what I have coded:
/*
* This is a program that determines the gross pay for employees of a
* company that pays "straight time" for the first 40 hours and "time
* and a half" for all hours excess. The program asks the user to
* input the hours worked and the rate per hour.
*/
// Imports.
import java.text.DecimalFormat;
import javax.swing.*;
public class SalaryCalculator
{
public static void main( String[] args )
{
// Ask for number of employees.
String num = JOptionPane.showInputDialog( "How many employees?" );
int employees = Integer.parseInt( num );
for (int counter = 0; counter != employees; counter++)
{
// Ask for employee info.
String name = JOptionPane.showInputDialog ( "Enter employee name:" );
String rate = JOptionPane.showInputDialog( "Enter standard rate per hour in $:" );
String hours = JOptionPane.showInputDialog( "Enter number of hours worked:" );
// Convert string to double.
double money = Double.parseDouble( rate );
double time = Double.parseDouble( hours );
// Create number format and text area.
DecimalFormat noDecimal = new DecimalFormat( "0.00" );
JTextArea outputArea = new JTextArea( 30, 30 );
// Format text area.
outputArea.append( "Name \t Rate \t Hours \t Total \n\n" );
// Calculations and all.
if ( time <= 40 )
{
outputArea.append( name + "\t" + "$"
+ money + "\t"
+ hours + "\t" + "$"
+ noDecimal.format( money * time ) + "\n" );
}
else if( time > 40 )
{
outputArea.append( name + "\t" + "$"
+ money + "\t"
+ hours + "\t" + "$"
+ noDecimal.format( ( money * 1.5 ) * time ) + "\n" );
}
// Output.
JOptionPane.showConfirmDialog( null,
outputArea, "Gross Pay", JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE );
}
}
}
When the code is executed, it asks for the number of employees. Say I enter 2, for example. The program then proceeds to ask the employee name, pay per hour, and number of hours worked. When I enter all of these, it shows the output nicely in a window like I want.
Picture: Data set 1.
After that, it again asks for employee name, pay, and hours (since I said there are 2 employees). This is where my problem is. When I input the second set of data, it replaces the first in the result window.
Picture: Data set 2 replaces set 1.
I want it to be displayed in a new line below the first on the same window, without having the first omitted.
This is my first time posting on stack overflow. Any help will be greatly appreciated!
You're creating a new JTextArea with each iteration of the loop. Don't do that. Create the JTextArea before the loop, and use the same one.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
I am working on a project for coverting a discord bots output into a csv file for better tracking i keep geting a data parsing error and was wondering if anyone could spot the issue
Main.java:110: error: reached end of file while parsing
}
^
1 error
First, the program prompts the user to enter the name of the CSV file, which is then stored in a variable called fileName. Next, it creates a new CSV file using this name and a BufferedWriter.
// prompt the user to name the CSV file
System.out.print("Enter the name of the CSV file: ");
Scanner scanner = new Scanner(System.in);
String fileName = scanner.nextLine();
// create the CSV file
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
The program then writes the header row to the CSV file:
// write the header row to the CSV file
writer.write("Employee Name,Shift ID,Hours,Minutes,Seconds,Shift start date");
writer.newLine();
It initializes variables totalHours, totalMinutes, and totalSeconds to keep track of the totals for each employee. It also initializes a flag called done to indicate when the program should stop.
// initialize variables to keep track of totals
int totalHours = 0;
int totalMinutes = 0;
int totalSeconds = 0;
// initialize a flag to indicate whether the program is done
boolean done = false;
The program then enters a loop that continues until the done flag is set to true. Inside the loop, it prompts the user to enter the name of the employee and the shift data. The program then extracts the shift ID and duration from the shift data by using the substring method. It stores the shift ID in a variable called shiftId and the duration in a variable called durationString.
// extract the shift ID and duration from the shift data
String shiftId = shiftData.substring(0, shiftData.indexOf(" "));
String durationString = shiftData.substring(shiftData.indexOf("Duration: ") + 10, shiftData.indexOf(" Started: "));
Next, it parses the duration into hours, minutes, and seconds. It first checks whether the duration string contains the word "hour". If it does, the duration is more than an hour. In this case, it extracts the number of hours by using the substring method and stores it in a variable called hours. It then extracts the minutes and seconds by using the substring method and storing them in variables called minutes and seconds, respectively.
If the duration string does not contain the word "hour", it means the duration is less than an hour. In this case, the program extracts the minutes and seconds in the same way as before and stores them in the minutes and seconds variables.
// parse the duration into hours, minutes, and seconds
int hours = 0;
int minutes = 0;
int seconds = 0;
if (durationString.contains("hour")) {
// the duration is more than an hour
hours = Integer.parseInt(durationString.substring(0, durationString.indexOf(" hour")));
String minutesAndSeconds = durationString.substring(durationString.indexOf(" hour") + 6);
if (minutesAndSeconds.contains("minute")) {
// the duration has both hours and minutes
minutes = Integer.parseInt(minutesAndSeconds.substring(0, minutesAndSeconds.indexOf(" minute")));
seconds = Integer.parseInt(minutesAndSeconds.substring(minutesAndSeconds.indexOf(" minute") + 8, minutesAndSeconds.indexOf(" second")));
} else {
// the duration has only hours
seconds = Integer.parseInt(minutesAndSeconds.substring(0, minutesAndSeconds.indexOf(" second")));
}
} else {
// the duration is less than an hour
minutes = Integer.parseInt(durationString.substring(0, durationString.indexOf(" minute")));
seconds = Integer.parseInt(durationString.substring(durationString.indexOf(" minute") + 8, durationString.indexOf(" second")));
}
Next, the program parses the start date from the shift data and stores it in a variable called startDate. It uses the substring method to extract the start date string and a SimpleDateFormat object to parse the start date string into a Date object.
// parse the start date from the shift data
String startDateString = shiftData.substring(shiftData.indexOf("Started: ") + 9, shiftData.indexOf(" Ended: "));
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM dd, yyyy hh:mm a");
Date startDate = dateFormat.parse(startDateString);
Finally, the program writes the employee name, shift ID, hours, minutes, seconds, and start date to the CSV file, separated by commas. It also updates the totalHours, totalMinutes, and totalSeconds variables by adding the hours, minutes, and seconds for the current shift.
// write the data to the CSV file
writer.write(employeeName + "," + shiftId + "," + hours + "," + minutes + "," + seconds + "," + startDate.toString());
writer.newLine();
// update the totals
totalHours += hours;
totalMinutes += minutes;
totalSeconds += seconds;
After writing the shift data to the CSV file, the program prompts the user to enter a number indicating what to do next. If the user enters 1, the program continues to enter more shifts for the same employee. If the user enters 2, the program writes the totals for the previous employee to the CSV file, resets the totals, and prompts the user to enter shifts for a new employee. If the user enters 3, the program writes the totals for the previous employee to the CSV file, closes the file, and sets the done flag to true to exit the loop. If the user enters any other number, the program prompts the user again.
// ask the user what to do next
System.out.print("Enter 1 to enter more shifts for this employee, 2 to enter shifts for a new employee, or 3 to save and close the file: ");
int action = scanner.nextInt();
scanner.nextLine(); // consume the newline character
if (action == 1) {
// continue entering shifts for the same employee
} else if (action == 2) {
// write the totals for the previous employee to the CSV file
writer.write(employeeName + " Total," + totalHours + "," + totalMinutes + "," + totalSeconds);
writer.newLine();
// reset the totals
totalHours = 0;
totalMinutes = 0;
totalSeconds = 0;
} else if (action == 3) {
// write the totals for the previous employee to the CSV file
writer.write(employeeName + " Total," + totalHours + "," + totalMinutes + "," + totalSeconds);
writer.newLine();
// close the file and set the done flag to true
writer.close();
done = true;
} else {
// invalid input, ask the user again
System.out.println("Invalid input, please try again.");
}
Finally, the program closes the Scanner object and exits.
}
// close the scanner
scanner.close();
}
}
i have tried using a diffrent way of inputing as a csv and get the same result.
the bracket here
}//remove this bracket
// close the scanner
scanner.close();
}}
So it's been about 6 months since I've done anything with coding as well as I'm still relatively new to it. I'm doing some review and the program asks for several attributes, in which one is a string asking for an employee's ID #. It is supposed be in a loop, in which the loop is terminated when the user enters 0 for their employee ID. I have the program working up until this point and I haven't created the loop yet which is where I am stuck.
`import java.util.Scanner;`
`public class PayrollTester {`
`public static void main(String[] args) {`
`String empID;`
`float gross;`
`float ste;`
`float fed;`
`Scanner scnr = new Scanner(System.in);`
`System.out.println("Enter your Employee ID: ");`
`empID = scnr.nextLine();`
`System.out.println("Enter your Gross Pay: ");`
`gross = scnr.nextFloat();`
`System.out.println("Enter your State Tax Rate: ");`
`ste = scnr.nextFloat();`
`System.out.println("Enter your Federal Tax Rate: ");`
`fed = scnr.nextFloat();`
`Payroll empID1 = new Payroll(empID, gross, ste, fed);`
`System.out.println("The Net Pay for Employee " +
empID1.getEmplyeID() + " is " + empID1.calcNetPay());`
`}`
`}`
You can just do a while(true) loop and then you have an if statement right after they enter their employee id that checks to see if the value they entered is equal to 0.
while(true){
//get their employee id
if (empiID.equals("0")){
break;
}
//get more user inputs
}
import javax.swing.JOptionPane;
public class Minutes {
public static void main(String[] args) {
double BasePlanCost = 20;
final double BaseCostPerMinute=0.15;
double MinutesUsed = Double.parseDouble(JOptionPane.showInputDialog("Please enter the amount of minutes Used: "));
double CostForMinutes = BaseCostPerMinute * MinutesUsed;
double GrandTotal = BasePlanCost + CostForMinutes;
JOptionPane.showMessageDialog(null, String.format("$%.2f","**IST Wireless Receipt**","\n","Base Plan Cost:" +BasePlanCost,"/n","Cost For Minutes Used: "+ CostForMinutes,"/n","Grand Total :" +GrandTotal));
}
}
This program inputs the amount of minutes the user enters and calculates the grand total by adding the CostForMinutes and BasePlanCost.
CostForMinutes is calculated by multiplying the minutes the user enters and the BaseCostPerMinute. The out is all the numbers outputted by two decimal places and outputted as a receipt.
When I compile the program it lets me input the amount of minutes but the code collapses and gives me this error
exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.String
can anyone help me out?
EDIT this is what I want the output to look like
http://i.stack.imgur.com/CubfC.png
You have
String.format("$%.2f","**IST Wireless Receipt**",
This means you want to format the second argument which is a String using %.2f which is a float format which won't work.
You need to re-organize your format to be first and the values you want to format after it.
String.format("**IST Wireless Receipt**%n" +
"Base Plan Cost: $%.2f%n" +
"Cost For Minutes Used: $%.2f%n" +
"Grand Total: $%.2f%n",
BasePlanCost, CostForMinutes, GrandTotal)
Try to organize your message as:
String message = String.format(
"**IST Wireless Receipt** \n" +
" Base Plan Cost:$ %.2f \n" +
" Cost For Minutes Used: $ %.2f \n" +
" Grand Total : $ %.2f", BasePlanCost, CostForMinutes, GrandTotal);
JOptionPane.showMessageDialog(null, message);
I recommended you to read the code conventions of the java language
http://www.oracle.com/technetwork/java/codeconventions-135099.html
I am using a while loop and getting data from a text file and using classes to reference each string. I don't have any issues getting the values for each string and printing it out.
However, I am confused on how to use System.out.printf(....) to put all of the strings I need in one line while using a loop.
For example, let's say the text file was:
I
like
to
use
computers
I want to use a loop to print out the words into one string and I may have different spacing between each word.
The code I have so far:
while (!readyOrder.isEmpty()) {
s = readyOrder.poll();
System.out.printf(s.getQuantity() + " x " + s.getName()
+ "(" + s.getType() + ")" + " "
+ s.getPrice() * s.getQuantity());
System.out.println(" ");
total = total + s.getPrice() * s.getQuantity();
}
And the output should be:
1_x_The Shawshank Redemption_______(DVD)________________19.95
The underlined spaces are where the spaces should be and how long they should be.
How can I use printf to do that?
I think you need to use the string padding functionality of printf. For example %-30s formats to width of 30 characters, - means left justify.
for (Stock s : Arrays.asList(
new Stock(1, "The Shawshank Redemption", 100, "DVD"),
new Stock(2, "Human Centipede", 123, "VHS"),
new Stock(1, "Sharknado 2", 123, "Blu ray"))) {
System.out.printf("%2d x %-30s (%-7s) %5.2f\n",
s.getQuantity(), s.getName(), s.getType(),
s.getPrice() * s.getQuantity());
}
Output
1 x The Shawshank Redemption (DVD ) 100.00
2 x Human Centipede (VHS ) 246.00
1 x Sharknado 2 (Blu ray) 123.00
This is the format my text is in:
15no16no17yes the parents who have older children always tell you the next stage is worse.18yes using only their hands and feet make some of the worst movies in the history of the world.19no
So the basic format is this:
number yes|no text(may/may not be there) repeated
The text after yes or no can be empty, or can start with a space. (I have tried to illustrate this above).
The code I have works for this format:
number yes|no repeated
More examples of text to parse:
30no31yesapproximately 278 billion miles from anything.32no33no34no
30no31yesapproximately 278 billion miles from anything32no33yessince the invention of call waiting34yesGravity is a contributing factor in 73 percent of all accidents involving falling objects.
35yesanybody who owns hideous clothing36yes if you take it from another person's plate37yes172 miles per hour upside down38yesonly more intelligent39yes any product including floor wax that has fat in it
35no36yestake it from another person's plate37yes172 miles per hour upside down38no39no
35no36no37yes172 miles per hour38no39no
35no36no37yesupside down38no39no
How do I modify my code?
String regex = "^(\\d+)(yes|no)";
Pattern p = Pattern.compile(regex);
while(input.hasNextLine()) {
String line = input.nextLine();
String myStr = line;
Matcher m = p.matcher(myStr);
while(m.find()) {
String all = m.group();
String digits = m.group(1);
String bool = m.group(2);
// do stuff
myStr = myStr.substring(all.length());
m.reset(myStr);
} // end while
} // end while
I tried using String regex = "^(\\d+)(yes|no)(.*)"; but the problem is that it captures everything after a yes or no.
What do I do?
PS: Please let me know if anything is unclear and I'll provide more explanations.
Try this. I think it will work. In the end of the parsing, you will have a List of Answers. Now, you just need to make some modifications to return this List and use its answers. My algorithm just detects all the answers and where they start in the main String and with this information, slice the text. So, the algorithm have two steps (1: bounds detection, 2: string slicing). I made some comnents in my code. Hope it works.
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* #author David Buzatto
*/
public class ASimpleParser {
public static void main( String[] args ) {
new ASimpleParser().exec();
}
public void exec() {
String[] in = {
"30no31yesapproximately 278 billion miles from anything.32no33no34no",
"30no31yesapproximately 278 billion miles from anything32no33yessince the invention of call waiting34yesGravity is a contributing factor in 73 percent of all accidents involving falling objects.",
"35yesanybody who owns hideous clothing36yes if you take it from another person's plate37yes172 miles per hour upside down38yesonly more intelligent39yes any product including floor wax that has fat in it",
"35no36yestake it from another person's plate37yes172 miles per hour upside down38no39no",
"35no36no37yes172 miles per hour38no39no",
"35no36no37yesupside down38no39no"
};
Pattern p = Pattern.compile( "(\\d+)(yes|no)" );
List<Answer> allAnswers = new ArrayList<Answer>();
for ( String s : in ) {
List<Answer> answers = new ArrayList<Answer>();
Matcher m = p.matcher( s );
// step 1: detecting answer bounds (start)
while ( m.find() ) {
Answer a = new Answer();
a.answerStart = m.group();
a.number = m.group( 1 );
a.yesOrNo = m.group( 2 );
a.startAt = s.indexOf( a.answerStart );
answers.add( a );
}
// step 2: slicing
for ( int i = 0; i < answers.size(); i++ ) {
Answer a = answers.get( i );
// needs to compare to the right one, the will have the right bounds
if ( i != answers.size() - 1 ) {
Answer rightAnswer = answers.get( i + 1 );
a.text = s.substring( a.startAt + a.answerStart.length(), rightAnswer.startAt );
} else { // int the last answer, the right bound is the end of the main String. s.length() may be ommited.
a.text = s.substring( a.startAt + a.answerStart.length(), s.length() );
}
}
allAnswers.addAll( answers );
}
// just iterating over the answers to show them.
for ( Answer a : allAnswers ) {
System.out.println( a );
}
}
// a private class to contain the answers data
private class Answer {
String answerStart;
String number;
String yesOrNo;
String text;
int startAt;
#Override
public String toString() {
return "Answer{" + "number=" + number + ", answer=" + yesOrNo + ", text=" + text + ", startAt=" + startAt + '}';
}
}
}