Delete one scanner, Payroll program Week 3 [duplicate] - java

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 7 years ago.
How am I able to get rid of one scanner? If I do use just one scanner the after the weekly_pay is output is:
Employee Name
Enter the hours worked for the week.
The program skips right over asking for the employee name variable. With both scanners it does indeed loop asking for the employee name as it should.
//Week 3 Assignment
package weeklypay2;
import java.util.Scanner; // importing the Java utility class scanner
public class WeeklyPay2 // class WeeklyPay
{
//main method
public static void main(String[] args)
{
Scanner Scanner = new Scanner(System.in);
Scanner Scanner1 = new Scanner(System.in);
String employee_name = null; // variable for employee name
double hours_worked = 0, // variable for weekly hours worked
pay_rate = 0, // variable for pay rate per hour
weekly_pay = 0; // weekly pay = hours * pay_rate
while (employee_name!="stop")
{
System.out.println("");
System.out.println("Employee Name"); // prompt, employees name
employee_name = Scanner1.nextLine();
if (employee_name.equalsIgnoreCase("stop"))
{
System.out.print("Exiting Program");
break;
} // ends if statement
else
{
System.out.println("Enter the hours worked for the week");
//prompt, hours worked for the current week
pay_rate = Scanner.nextDouble();
while(pay_rate < 0.01)
{
System.out.print("ERROR!!, Input a postive number: \n");
pay_rate = Scanner.nextDouble();
}
System.out.println("Enter the employees hourly pay rate");
// prompt, the employees pay rate
hours_worked = Scanner.nextDouble();
while(hours_worked < 0.01)
{
System.out.print("ERROR!!, Input a postive number: \n");
hours_worked = Scanner.nextDouble();
}
weekly_pay = (double) hours_worked * (double) pay_rate; // setting the variable weekly_pay
System.out.println(employee_name + "'s weekly pay is $" + weekly_pay ); // output the employees name and weekly pay
}
}
Scanner.close();
Scanner1.close();
} //ends main method
} //ends class WeeklyPay

Well the first thing I would say is be careful naming your scanner. Don't start that with a capital. Now a big thing is you don't want to compare strings using !=, this is not intended for string variables. There is a fun method for comparing strings that would be .equals() or .equalsIgnoreCase() depending if you want it non-case sensitive. Now after changing those few things in your code it works just fine. Also just a heads up Java also includes a method for formatting currency. You're pay numbers were missing a decimal. If you look at the NumberFormat I added after the scanner and then look at the println at the end you can see its very simple to use.
import java.text.NumberFormat;
import java.util.Scanner; // importing the Java utility class scanner
public class WeeklyPay2 // class WeeklyPay
{
//main method
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
NumberFormat format = NumberFormat.getCurrencyInstance();
String employee_name = "";
double hours_worked = 0, // variable for weekly hours worked
pay_rate = 0, // variable for pay rate per hour
weekly_pay = 0; // weekly pay = hours * pay_rate
while (!employee_name.equalsIgnoreCase("stop"))
{
System.out.println();
System.out.print("Employee Name: ");
employee_name = scanner.nextLine();
if (employee_name.equalsIgnoreCase("stop"))
{
System.out.print("Exiting Program");
break;
} // ends if statement
else
{
System.out.print("Enter the hours worked for the week: ");
//prompt, hours worked for the current week
pay_rate = scanner.nextDouble();
while(pay_rate < 0.01)
{
System.out.print("ERROR!!, Input a postive number: ");
pay_rate = scanner.nextDouble();
}
System.out.print("Enter the employees hourly pay rate: ");
// prompt, the employees pay rate
hours_worked = scanner.nextDouble();
while(hours_worked < 0.01)
{
System.out.print("ERROR!!, Input a postive number: \n");
hours_worked = scanner.nextDouble();
}
weekly_pay = (double) hours_worked * (double) pay_rate; // setting the variable weekly_pay
System.out.println(employee_name + "'s weekly pay is: " + format.format(weekly_pay)); // output the employees name and weekly pay
scanner.nextLine();
}
}
scanner.close();
} //ends main method
} //ends class WeeklyPay
And this is the output we would see:
Oh, PS: Keep the program cleaner by prompting for the input on the same line, more intuitive and better to look at. By all means add a line break after the input but not before :)

use Scanner1.nextLine() after getting the value for hours worked.
Refer modified code below:
import java.util.Scanner; // importing the Java utility class scanner
public class WeeklyPay2 // class WeeklyPay
{
//main method
public static void main(String[] args) {
Scanner Scanner1 = new Scanner(System.in);
String employee_name = null; // variable for employee name
double hours_worked = 0, // variable for weekly hours worked
pay_rate = 0, // variable for pay rate per hour
weekly_pay = 0; // weekly pay = hours * pay_rate
//Scanner1.useDelimiter("//n");
while (true) {
System.out.println("");
System.out.println("Employee Name"); // prompt, employees name
employee_name = Scanner1.nextLine();
if (employee_name.equalsIgnoreCase("stop"))
{
System.out.print("Exiting Program");
break;
}// ends if statement
else {
System.out.println("Enter the hours worked for the week");
//prompt, hours worked for the current week
pay_rate = Scanner1.nextDouble();
while (pay_rate < 0.01) {
System.out.print("ERROR!!, Input a postive number: \n");
pay_rate = Scanner1.nextDouble();
}
System.out.println("Enter the employees hourly pay rate");
// prompt, the employees pay rate
hours_worked = Scanner1.nextDouble();
while (hours_worked < 0.01) {
System.out.print("ERROR!!, Input a postive number: \n");
hours_worked = Scanner1.nextDouble();
//Scanner1.
}
Scanner1.nextLine();
weekly_pay = (double) hours_worked * (double)
pay_rate; // setting the variable weekly_pay
System.out.println(employee_name + "'s weekly pay is $" + weekly_pay); // output the employees name and weekly pay
}
}
Scanner1.close();
} //ends main method
}//ends class WeeklyPay

Related

Java For Loop not ending with Sentinel

I am creating a program that takes in employee payroll information and then displays the average and total afterwards. Everything seems to be working correctly except for the fact I cannot get the program to end when I enter the sentinel value of -1 for the hours worked so that the program can display the total and average of the employees. Any help is greatly appreciated.
import java.util.Scanner;
public class PayrollDo
{
public static void main(String[] args)
{
int hoursWorked = 0;
int grossPay = 0;
int empCounter = 0;
int total = 0;
Scanner keyboard = new Scanner(System.in);
do {
total = total + grossPay; // add gross to total
empCounter = empCounter + 1; // incriment counter
System.out.print("Enter hours worked: ");
hoursWorked = keyboard.nextInt();
System.out.print("Enter hourly wage: ");
int hourlyWage = keyboard.nextInt();
//System.out.println("Grosspay is " + (hourlyWage * hoursWorked));
keyboard.nextLine();
System.out.println("Enter employee name ");
String name = keyboard.nextLine();
} while(hoursWorked != -1);
// if user entered at least one employee
if (empCounter != 0) {
// use number with decimal point to calculate average of employees
int average = (int) total / empCounter;
// display total and average (with two digits of precision)
System.out.printf("%nTotal of the %d employees entered is %d%n",
empCounter, total);
System.out.printf("Employee average is " + average);
}
else {
// no employees were entered, so output appropriate message
System.out.println("No employees were entered");
}
}
}
Test soon after entering the value whether it is -1 or not
System.out.print("Enter hours worked: ");
hoursWorked = keyboard.nextInt();
if (hoursWorked == -1) break;
edit
I think you will also have trouble with Integer division http://stackoverflow.com/questions/4685450/why-is-the-result-of-1-3-0
You could restructure your do loop to put the hoursWorked input last (otherwise you have to complete the entries) - and also, add a conditional to reject all entries that cycle, otherwise empCounter is off by one. And I think the total calculation needs reworking too:
do {
System.out.println("Enter employee name ");
String name = keyboard.nextLine();
System.out.print("Enter hourly wage: ");
int hourlyWage = keyboard.nextInt();
System.out.print("Enter hours worked: ");
hoursWorked = keyboard.nextInt();
keyboard.nextLine();
if (hoursWorked != -1) {
total = total + (hourlyWage * hoursWorked); //
empCounter = empCounter + 1; // incriment counter
}
} while(hoursWorked != -1);
In cases like this it can be simpler to have a question like "More Employees? (y/n)" that is used to terminate the loop, using a boolean flag as the while terminator.

Skips over system out, scan nextLine, and if loops

New here (and to Java!). I've searched around the site for an answer to my problem but came up naught. This program executes up to the scan.nextDouble statement.
If I enter a salary value such as "8," I get:
/////OUTPUT/////
Enter the performance rating (Excellent, Good, or Poor):
Current Salary: $8.00
Amount of your raise: $0.00
Your new salary: $8.00
/////END OF OUTPUT/////
So obviously, my following scan.nextLine and all the if-else statements are bypassed. What am I missing?
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary
{
public static void main(String[] args)
{
double currentSalary; // employee's current salary
double raise = 0; // amount of the raise
double newSalary = 0; // new salary for the employee
String rating; // performance rating
String rating1 = new String("Excellent");
String rating2 = new String("Good");
String rating3 = new String("Poor");
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.nextLine();
// Compute the raise using if ...
if (rating.equals(rating1))
raise = .06;
else
if (rating.equals(rating2))
raise = .04;
else
if (rating.equals(rating3))
raise = .015;
else
newSalary = currentSalary + currentSalary * raise;
// Print the results
{
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary: " + money.format(newSalary));
System.out.println();
}
}
}
When you scan input using scanner.nextDouble() it takes only the float value and leaves the new line character in the buffer so after that when you do scanner.nextLine(() it takes the new line character and returns empty string.Put another scanner.nextLine() before scanning the next line to eat up the new line character
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
scan.nextLine();
rating = scan.nextLine();
Scanner.nextDouble() just reads the next available double value and does not by itself point to next line.
use a dummy scanner.nextLine() before your actual one. that lets your cursor point to next line from which your scanner.nextline() takes the input.
-cheers :)

How can I restart my java program based on user input?

I'm writing a program used to calculate the total sales of employees in a small business, and am trying to figure out how to restart the program based on a user input of y/n. I know that loops are what I need to use here, but need a push in the right direction.
Code:
import java.util.Scanner;
public class calcMain {
public static void main(String[]args){
double totalPay = 0, itemOne = 239.99, itemTwo = 129.75, itemThree = 99.95, itemFour = 350.89, commission;
int weeklyBonus = 200, numSold;
String employee1, employee2, employee3, employee4, yn;
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the salesperson's name: ");
employee1 = kb.nextLine();
System.out.println("Please enter the number of Item 1 sold: ");
numSold = kb.nextInt();
totalPay += (itemOne * numSold);
System.out.println("Please enter the number of Item 2 sold: ");
numSold = kb.nextInt();
totalPay += (itemTwo * numSold);
System.out.println("Please enter the number of item 3 sold: ");
numSold = kb.nextInt();
totalPay += (itemThree * numSold);
System.out.println("Please enter the number of item 4 sold: ");
numSold = kb.nextInt();
totalPay += (itemFour * numSold);
System.out.println("The total weekly earnings for " +employee1+ " are: " +totalPay);
System.out.println("Would you like to input the sales of another employee? (y/n)");
yn = kb.next();
}
}
Put all the code inside a while loop that says while (yn.equalsIgnoreCase("y"))
Don't forget to initialize yn to y!
Second solution:
Modify the code so that it returns a string, and if the user inputs y, return y, or if the user inputs n, return n.
Put all that code inside a method (lets call it method x for now)
public static void main(String[] args) {
while(x().equalsIgnoreCase("y")){}
}
Using a do-while loop (while loop should have the same effect) and ask for (y/n) at the end.
Like this:
String yn;
do
{
// Your code here
// Ask for confirmation
}
while (yn.equals("y"));

monthly payment calculator

I have some code which I find to keep giving me a dividing by 0 error.
It is suppose to calculate the monthly payment amount!
import java.io.*;
public class Bert
{
public static void main(String[] args)throws IOException
{
//Declaring Variables
int price, downpayment, tradeIn, months,loanAmt, interest;
double annualInterest, payment;
String custName, inputPrice,inputDownPayment,inputTradeIn,inputMonths, inputAnnualInterest;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
//Get Input from User
System.out.println("What is your name? ");
custName = dataIn.readLine();
System.out.print("What is the price of the car? ");
inputPrice = dataIn.readLine();
System.out.print("What is the downpayment? ");
inputDownPayment = dataIn.readLine();
System.out.print("What is the trade-in value? ");
inputTradeIn = dataIn.readLine();
System.out.print("For how many months is the loan? ");
inputMonths = dataIn.readLine();
System.out.print("What is the decimal interest rate? ");
inputAnnualInterest = dataIn.readLine();
//Conversions
price = Integer.parseInt(inputPrice);
downpayment = Integer.parseInt(inputDownPayment);
tradeIn = Integer.parseInt(inputTradeIn);
months = Integer.parseInt(inputMonths);
annualInterest = Double.parseDouble(inputAnnualInterest);
interest =(int)annualInterest/12;
loanAmt = price-downpayment-tradeIn;
//payment = loanAmt*interest/a-(1+interest)
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
//Output
System.out.print("The monthly payment for " + custName + " is $");
System.out.println(payment);
// figures out monthly payment amount!!!
}
}
the problem occurs when attempting to set the payment variable.
i don't understand why it keeps coming up with dividing by 0 error.
You have declared your variables as Int so 1/interest and 1/(interest*Math.pow(1+interest,-months)) will return 0. Change the type of your variables to float or double.
One suggestion to you, is that you should learn to "backwards slice" your code.
This means that when you see that you're getting a DivideByZeroException you should look at your code, and say, "why could this happen?"
In your case, let's look at this:
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
So, now, Math.pow will never return anything zero (as it's a power), so it must be the case that interestis zero. Let's find out why:
interest =(int)annualInterest/12;
So now, integer division in Java truncates. This means that if you have .5 it will be cut off, and turned into zero. (Similarly, 1.3 will be truncated to 0).
So now:
annualInterest = Double.parseDouble(inputAnnualInterest);
This implies that you are passing in something that gets parsed to a value that is less than 12. If it were greater than 12 then you would get something else.
However, you might just be passing in an invalid string, for example, passing in "hello2.0" won't work!
This will be rounding always to 0. So it is trowing exception.
(1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
Use float type instead of int. Learn how they works.
package computeloan;
import java.util.Scanner;
public class ComputeLoan {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Enter Yearly Interest Rate : ");
double annualIntersetRate = input.nextDouble();
double monthlyIntersetRate = annualIntersetRate / 1200;
System.out.print(" Enter Number of years : ");
int numberOfYears = input.nextInt();
// Enter loan amount
System.out.print(" Enter Loan Amount : ");
double loanAmount = input.nextDouble();
double monthlyPayment = loanAmount * monthlyIntersetRate /(1-1/Math.pow(1+monthlyIntersetRate,numberOfYears*12 ));
double totalPayment = monthlyPayment * numberOfYears * 12;
//Calculate monthlyPaymeent and totalPayment
System.out.println(" The Monthly Payment Is : " +(int)(monthlyPayment*100) /100.0);
System.out.println(" The Total Payment Is : " +(int)(totalPayment*100) /100.0 );
}
}

Java loan calculator

I'm trying to code a loan calculator. I seem to be having issues. I am trying to get an input from the user and validate the input. I know I am doing it wrong the problem is I'm scratching my head wondering how to do it right.
I get a red line on the d = getDouble(sc, prompt); and the i = getInt(sc, prompt); which I understand I don't have that coded correctly. I'm just unsure how to go about fixing it.
I also have to validate the continue statement which I wasn't to sure the best way to go about that and finally the instructor expects the code to be 80 lines or less which I am right about 80 lines. I guess I'm looking for a better way to do this but being new I'm scratching my head and I'm hoping someone can lend a hand.
As always I really appreciate the help.
import java.util.Scanner;
import java.text.NumberFormat;
public class LoanCalculator
{
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false;
while(isValid == false);
{
d = getDouble(sc, prompt);
if (d <= min)
{
System.out.println("Error! Number must be greater tha 0.0");
}
else if (d >= max)
{
System.out.println("Error number must be less than 1000000.0");
}
else
isValid = true;
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isvalid = false;
while(isvalid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println("Error! Number must be more than 0");
else if (i >= max)
System.out.println("Error! Number must be less than 100");
else
isvalid = true;
}
}
public static void main(String[] args)
{
System.out.println("Welcome to the loan calculator");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
int months = years * 12;
double monthlyPayment = loanAmount * interestRate/
(1 - 1/Math.pow(1 + interestRate, months));
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(3);
System.out.println("RESULST");
System.out.println("Loan Amount" + currency.format(loanAmount));
System.out.println("Yearly interest rate: " + percent.format(interestRate));
System.out.println("Number of years: " + years);
System.out.println("Monthly payment: " + currency.format(monthlyPayment));
System.out.println();
System.out.println("Continue? (y/n): ");
choice =sc.next();
System.out.println();
}
}
}
You haven't made the implementation of your getDouble(Scanner,String) and getInt(Scanner,String) that's why you're getting the red line.
since you already have a scanner, and prompt string change it to this
System.out.print(prompt);
d = sc.nextDouble();
and for the integer
System.out.print(prompt);
i = sc.nextInt();
I think getDouble and getInt are string functions so you would have to get a string first then call those methods. However, since you have a scanner, I assume you want to use that with the nextXXX methods:
Scanner sc = new Scanner (System.in);
double d = sc.nextDouble();
You can use this complete snippet for educational purposes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter your double: ");
double d = sc.nextDouble();
System.out.print("Enter your integer: ");
int i = sc.nextInt();
System.out.println("You entered: " + d + " and " + i);
}
}
Transcript:
Enter your double: 3.14159
Enter your integer: 42
You entered: 3.14159 and 42
Basically, the process is:
Instantiate a scanner, using the standard input stream.
Use print for your prompts.
Use the scanner nextXXX methods for getting the input values.
A little more assistance here, based on your comments.
In your main function, you have:
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0)
and that function has the prototype:
public static double getDoubleWithinRange(
Scanner sc, String prompt, double min, double max)
That means those variables in the prototype will be set to the values from the call. So, to prompt for the information, you could use something like (and this is to replace the d = getDouble(sc, prompt); line):
System.out.print(prompt);
double d = sc.nextDouble();
And there you have it, you've prompted the user and input the double from them. The first line prints out the prompt, the second uses the scanner to get the input from the user.
As an aside, your checks for the minimum and maximum are good but your error messages have hard-coded values of 0 and 100K. I would suggest that you use the parameters to tailor these messages, such as changing:
System.out.println("Error! Number must be greater tha 0.0");
into:
System.out.println("Error! Number must be greater than " + min);
That way, if min or max change in future , your users won't get confused :-)
I'll leave it up to you to do a similar thing for the integer input. It is your homework, after all :-)

Categories

Resources