copying arrays from a method to main method - java

I am asked to write a program that requires three arrays in the main method. The program is supposed to calculate gross wages for given employee ids from user input of the pay rate and hours also from user input. Also, it is asking me to write a method calculateWages with three array parameters: hours, payRate, and wages, which calculates and stores the wages for each employee by multiplying the corresponding hours and pay rates.
Your program should display each employee number and ask the user to enter that employee's hours and pay rate. After getting the hours and pay rates for all employees, your program should call calculateWages. Next, your program should display each employee's identification number and gross wages. Note: the number of employees and the minimum wage should both be named constants.
public static void main(String[] args)
{
double[] employeeID = {5658845, 4520125, 7895122, 8777541, 8451277,1302850, 7580489}; //Employee IDs of which we are calculating gross wages for
double[] payRate = new double[7];
double[] employeeWages = new double[7];
double[] employeeHours = new double[7];
Scanner keyboard = new Scanner(System.in); //Needed for keyboard input
for (int i = 0; i<employeeID.length; i++)
{
System.out.println("Employee ID: " + employeeID[i]);
System.out.print("Enter the number of hours worked: ");
employeeHours[i]=keyboard.nextDouble();
//Get and validate hours from user.
while(employeeHours[i]<0)
{
System.out.println("Error. Hours worked must not be negative.");
System.out.print("Please enter hours worked: ");
employeeHours[i]=keyboard.nextDouble();
}
//Get and validate pay rate from employees.
System.out.print("Enter the pay rate of employee: ");
payRate[i]=keyboard.nextDouble();
while(payRate[i]<10.24)
{
System.out.println("Error. Minimum pay rate must be at least $10.24");
System.out.print("Please enter the pay rate: ");
payRate[i]=keyboard.nextDouble();
}
}
calculateWages(employeeWages, employeeHours, payRate);
System.out.println("Gross Wages:");
System.out.println();
for(int i=0;i<employeeID.length;i++)
{
System.out.printf("%-9d%-7s",employeeID[i],employeeWages[i]);
}
}
public static String[] calculateWages(double[] employeeWages, double[] inputHours,double[] payRate)
{
String[] formatWage = new String[7];
DecimalFormat formatter = new DecimalFormat("$###.00");
for(int i = 1;i<employeeWages.length;i++)
{
employeeWages[i]=inputHours[i]*payRate[i];
formatWage[i]=formatter.format(employeeWages[i]);
}
return formatWage;
}
}

calculateWages is returning an array so set an array equal to it
String [] result = calculateWages(employeeWages, employeeHours, payRate);

Related

Payroll Array Java Calculation

Hello guys, this is my first time i post something in here and i just started learning java. This is my assignment and i need to write a payroll code with array. However, i dont understand why i cant get it to work. Somehow, it only calculate the last employee, the first and second are not included. If you guys can help i'd appreciate it. Thank you!
public class ArrayIG
{
public static void main(String[] args)
{
final int NUM_EMPLOYEES = 3;
//creating array
int[]hours = new int[NUM_EMPLOYEES];
int[] employeeID = {5678459, 4520125, 7895122};
double payRate;
double wages = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your " + NUM_EMPLOYEES + " employees work hours and pay rate:");
//get the hours
for (int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.print("Employee #" + employeeID[i] + ": ");
hours[i] = keyboard.nextInt();
//get the hourly pay rate
System.out.print("Enter the pay rate: ");
payRate = keyboard.nextDouble();
wages = hours[i] * payRate;
}
//display wages
System.out.println("The hours and pay rates you entered are:");
for(int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.printf("The total wages for Employee #%d is $%.2f\n", employeeID[i], wages);
}
}
}
MY OUTPUT:
Enter your 3 employees work hours and pay rate:
Employee #5678459: 35
Enter the pay rate: 21
Employee #4520125: 37
Enter the pay rate: 18.5
Employee #7895122: 39
Enter the pay rate: 37.25
The hours and pay rates you entered are:
The total wages for Employee #5678459 is $1452.75
The total wages for Employee #4520125 is $1452.75
The total wages for Employee #7895122 is $1452.75
Either create an array of wages or calculate wages in loop where wages are being print. And you should do assignments on your own 😀
You're collecting 3 different hours but only storing them in one value. The same for the wages. What happens when you store them as an array?
import java.util.Scanner;
public class ArrayIG
{
public static void main(String[] args)
{
final int NUM_EMPLOYEES = 3;
//creating array
int[] hours = new int[NUM_EMPLOYEES];
int[] employeeID = {5678459, 4520125, 7895122};
double[] payRate = new double[NUM_EMPLOYEES];
double[] wages = new double[NUM_EMPLOYEES];
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your " + NUM_EMPLOYEES + " employees work hours and pay rate:");
//get the hours
for (int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.print("Employee #" + employeeID[i] + ": ");
hours[i] = keyboard.nextInt();
//get the hourly pay rate
System.out.print("Enter the pay rate: ");
payRate[i] = keyboard.nextDouble();
wages[i] = hours[i] * payRate[i];
}
//display wages
System.out.println("The hours and pay rates you entered are:");
for(int i = 0; i < NUM_EMPLOYEES; i++)
{
System.out.printf("The total wages for Employee #%d is $%.2f\n", employeeID[i], wages[i]);
}
}
}
You have 3 employees -> 3 wages.
But currently you're using only one variable to hold the wage: double wages = 0;
Hence its value is replaced for every loop.
You should create an array of length 3 to store the wages:
and in your loop, replace
wages = hours[i] * payRate;
With
wages[i] = hours[i] * payRate;
And print:
System.out.printf("The total wages for Employee #%d is $%.2f\n", employeeID[i], wages[i]);
You are setting the wage rate at each iteration. I.e. you are only ever recording a single state of wages. Then you are iterating and displaying that one wages variable, which will always be the last calculation.
Store each "wages" value in an array like you have done with hours and you should resolve your issue.

Formatting percentages with printf

import java.util.Scanner;
public class Taxes {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.printf("Enter the employees first name: ");
Scanner input = new Scanner(System.in);
String fName = input.nextLine();
System.out.printf("Enter the employees last name: ");
String lName = input.nextLine();
System.out.printf("Enter the hours worked for the week: ");
double hours = input.nextDouble();
System.out.printf("Enter the hourly pay rate: ");
double pay = input.nextDouble();
double gross = hours * pay;
System.out.printf("Enter the federal tax withholding: ");
double fed = input.nextDouble();
double fTax = gross * fed;
System.out.printf("Enter the state tax withholding: ");
double state = input.nextDouble();
double sTax = gross * state;
double Ttax = sTax + fTax;
double net = gross - Ttax;
System.out.printf(
"Employee Name:%s %s\n\nHours Worked:%s hours\n\nPay Rate:$%.2f\n\nGross pay:$%.2f\n\nDeductions: \n\n\tFederal Withholding:(%.2f%%)$%.2f \n\n"
+ "\tState Withholding:(%.2f%%)$%.2f\n\n\tTotal Witholding:$%.2f\n\nNet Pay:$%.2f",
fName, lName, hours, pay, gross, fed, fTax, state, sTax, Ttax, net);
input.close();
}
}
I need to declare two more variables to get the Federal and State tax withholdings to show as a percent.
Example They show as (00.20%) I need them to return as a whole percent like (20.00%)
I've tried declaring new variable at the bottom such as:
statewit = sTax * 100;
fedwit = fTax * 100;
to get the percents to return as I want but it tends to add that total to the net at the end.
Any help would be appreciated greatly, thanks!
Try this.
double percent=12.34;
System.out.printf("%.2f%%", percent);
// or in different convention "percent as number *100"
System.out.printf("%.2f%%", percent*100.0);
EDIT: Your Question can be divided in two:
Convention in which numbers are used (normal or percent scaled *100)
Real formatting to String
BTW Your code is long and has very little to FORMATTING.
Java has no special type for percent values. Types: double, BigDecimal can be used with his behaviour, or integer types too, if programmer keep integer convention
EDIT: thanks Costis Aivalis , comma corrected :)

Is this the correct syntax for inputing a string to an if statement or am i completely off?

package travelCost;
import java.util.Scanner;
public class travelCost {
public static void main(String[] args) {
//Scanner function
Scanner in = new Scanner(System.in);
//define problem variables
//first
double distance;
double mpg;
double pricePerGallon;
double milesPerKwh;
double pricePerKwh;
double totalCostGas;
double totalCostElec;
String type;
//Here i want the user to input a string and then based upon the answer //section into the for loop
System.out.println("Enter whether the car is 'elec' or 'gas': ");
type = in.next();
if (type.equals("elec"))
{
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the total Miles per Kwh: ");
milesPerKwh = in.nextDouble();
System.out.println("Enter the Total Price per Kwh: ");
pricePerKwh = in.nextDouble();
totalCostElec = (distance/milesPerKwh) * pricePerKwh;
System.out.printf("The trip is going to cost $%5.2f: ", totalCostElec);
} else if (type.equals("gas: ")
{
System.out.println("Enter the Miles per Gallon: ");
mpg = in.nextDouble();
System.out.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
System.out.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
totalCostGas = (distance/mpg) * pricePerGallon;
System.out.printf("The trip is going to cost $%5.2f", totalCostGas);
}else
{
System.out.println("Please resubmit entry");
}
System.out.println();
}
}
After the corrections which mentioned by Paul, here is the complete code:
travelCost.java
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double distance;
double mpg;
double pricePerGallon;
double milesPerKwh;
double pricePerKwh;
double totalCostGas;
double totalCostElec;
String type;
System.out.println("Enter whether the car is 'elec' or 'gas': ");
type = in.next();
if (type.equals("elec")) {
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the total Miles per Kwh: ");
milesPerKwh = in.nextDouble();
System.out.println("Enter the Total Price per Kwh: ");
pricePerKwh = in.nextDouble();
totalCostElec = (distance / milesPerKwh) * pricePerKwh;
System.out.printf("The trip is going to cost $%5.2f: ",
totalCostElec);
} else if (type.equals("gas")) {
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the Miles per Gallon: ");
mpg = in.nextDouble();
System.out
.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
System.out
.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
totalCostGas = (distance / mpg) * pricePerGallon;
System.out.printf("The trip is going to cost $%5.2f", totalCostGas);
} else {
System.out.println("Please resubmit entry");
}
System.out.println();
}
Input:
elec 100 10 2
Output:
The trip is going to cost $20.00:
make it
else if (type.equals("gas"))
There are 4 problems with this:
The line } else if (type.equals("gas: ") needs another ) at the end.
In the "gas" case, you are using the variable distance but you do not give it a value.
While if (type.equals("elec")) is the correct syntax (answering your question), it is usually better to write if ("elec".equals(type)) because this will not throw a NullPointerException if type == null.
It should be "gas", not "gas: ".
As Paul mentions, your if statement syntax is correct, but it is good practice to start with the hard coded strings ("elec" and "gas") in order to avoid NullPointerExceptions. As mentioned in the other answers, the if else should be using "gas" instead of "gas: ". To help avoid those kinds of errors, you might consider making "elec" and "gas" into static final String constants. If you use constants, you'll know that they are the same throughout your program. You might also want to call type.toLowerCase() in the event that the user enters the response in uppercase.

How do i calculate a whole bunch of different scanner inputs?

I'm not quiet sure how to go about doing the calculations for this. I have everything down right up until i'm trying to actually get the investment amount. I know what i have right now is wrong, but google isn't being super helpful for me, and my book just does not have what i need in order to complete this darn thing.
Here what i have right now
import java.util.Scanner;
class InvestmentCalculator {
public static void main(String[] args) {
// create a scanner object
Scanner input = new Scanner(System.in);
// Prompt user to enter investment amount
Scanner amount = new Scanner(System.in);
System.out.println("Enter Investment Amount");
while (!amount.hasNextDouble()) {
System.out.println("Only Integers");
amount.next();
}
//Promt user to enter interest rate
Scanner interest = new Scanner(System.in);
System.out.println("Enter Interest Percentage in decimals");
while (!interest.hasNextDouble()) {
System.out.println("Just like before, just numbers");
interest.next();
}
//Prompt user to enter number of years
Scanner years = new Scanner(System.in);
System.out.println("Enter Number of Years");
while (!years.hasNextDouble()) {
System.out.println("Now you are just being silly. Only Numbers allowed");
years.next();
}
//Compute Investment Amount
double future = amount * Math.pow((1 + interest), (years * 12));
//Display Results
System.out.println("Your future investment amount is " + future);
}
}
Any assistance would be very very helpful!
First of all amount, interest and years are Scanners, they are not numbers. The Scanner could contain any number of different types of content so it's impossible for something like Math.pow to know what it should do with them
You need to assign the values you read from the user to some variables.
I'd start by using a single Scanner, say called kb...
Scanner kb = new Scanner(System.in);
Then use this whenever you want to get a value from the user...
You input loops seem wrong to me, I'm not particularly experienced with the Scanner, so there is probably a better way to achieve this, but...
int invest = -1; // amount
double rate = -1; // percentage
int period = -1; // period
do {
System.out.println("Only Integers");
String text = kb.nextLine();
try {
invest = Integer.parseInt(text);
} catch (NumberFormatException exp) {
System.out.println("!! " + text + " is not an integer");
}
} while (invest == -1);
System.out.println(invest);
Once you have all the information you need, make your calculations with these primitive types...
double future = invest * Math.pow((1 + rate), (period * 12));
You don't have to use 4 different scanners for this because you are reading from the same stream.... Your code should be something like this -
import java.util.Scanner;
class InvestmentCalculator {
public static void main(String[] args) {
double amount=0;
int interest=0;
double years=0;
// create a scanner object
Scanner input = new Scanner(System.in);
// Prompt user to enter investment amount
Scanner amount = new Scanner(System.in);
System.out.println("Enter Investment Amount");
while (!input.hasNextDouble()) { // you say you only want integers and are
// reading double values??
System.out.println("Only Integers");
amount = input.nextDouble();
}
//Promt user to enter interest rate
System.out.println("Enter Interest Percentage in decimals");
while (!input.hasNextInt()) {
System.out.println("Just like before, just numbers");
interest= input.nextInt();
}
//Prompt user to enter number of years
System.out.println("Enter Number of Years");
while (!input.hasNextDouble()) {
System.out.println("Now you are just being silly. Only Numbers allowed");
years=input.nextDouble();
}
//Compute Investment Amount
double future = amount * Math.pow((1 + interest), (years * 12));
//Display Results
System.out.println("Your future investment amount is " + future);
}
}

Please Help me to solve the Simple Java program

The assignment is:
Write a program that provides 20% discount for member who purchase any two books at XYZ bookstore. (Hint: Use constant variable to the 20% discount.)
I have done the coding, but cannot prompt book name, and then show the discounted price. Please see my coding below and modify it as your needs.
import java.util.Scanner;
public class Book_Discount {
public static void main(String args[]) {
public static final double d = 0.8;
Scanner input = new Scanner(System.in);
int purchases;
double discounted_price;
System.out.print("Enter value of purchases: ");
purchases = input.nextInt();
discounted_price = purchases * d; // Here discount calculation takes place
// Displays discounted price
System.out.println("Value of discounted price: " + discounted_price);
}
}
For prompting the book name as well, you write something like:
/* Promt how many books */
System.out.print("How many books? ");
int bookCount = scanner.nextInt();
scanner.nextLine(); // finish the line...
double totalPrice = 0.0d; // create a counter for the total price
/* Ask for each book the name and price */
for (int i = 0; i < bookCount; ++i)
{
System.out.print("Name of the book? ");
String name = scanner.nextLine(); // get the name
System.out.print("Price of the book? ");
double price = scanner.nextDouble(); // get the price
scanner.nextLine(); // finish the line
totalPrice += price; // add the price to the counter
}
/* If you bought more than 1 book, you get discount */
if (bookCount >= 2)
{
totalPrice *= 0.8d;
}
/* Print the resulting price */
System.out.printf("Total price to pay: %.2f%n", totalPrice);

Categories