Salary calculation per hour (Java) - java

I've been trying to write a java program to calculate daily salary relying on hours worked per day. and if it was weekend or no. (boolean value).
The time the user need to write is 0824 it equals to 08:24 (no idea how to ask for hour:minutes pattern and subtract them).
I've been using only one loop to ask for payment Per Hour again and again if the user puts values lower than 28.00$ or higher than 100.00$.
When the program running after asking for paymentPerHour the program stops <terminated> is not shown.
Would appreciate any help. Thanks! :)
(don't pay attention to the class name)
package ouzanFirstProject;
import java.util.Scanner;
public class convertDecToBinary {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
int paymentPerHour , entryHour = 0 , exitHour = 0;
float totalHour= (exitHour-entryHour)/100;
boolean workedAtWeekend;
float salary = 0;
System.out.println("Please enter the hour you arrived to work (HHMM)");
entryHour=in.nextInt();
System.out.println("Please enter the hour you exit from work(HHMM)");
exitHour=in.nextInt();
System.out.println("Please enter payment per hour (between 28.00 and 100.00):");
paymentPerHour=in.nextInt();
while(paymentPerHour>0) {
if(paymentPerHour<28 ||paymentPerHour>100) {
System.out.println("Please enter payment per hour");
paymentPerHour=in.nextInt();
}
if(paymentPerHour>=28 &&paymentPerHour<=100) {
continue;
}
}
System.out.println("Did you work on weekend ? (True/False)");
workedAtWeekend=in.hasNext();
if(workedAtWeekend){
salary= (float) ((totalHour)*0.20+100);
}
else if (totalHour>=9) {
salary=(float) ((float)(totalHour)*paymentPerHour*1.5);
if(totalHour>11) {
salary = (float)((float)(totalHour)*paymentPerHour*2);
}
}
else if(totalHour<9) {
salary=(float)((float)(totalHour)*paymentPerHour*0.1);
if(totalHour<=1) {
salary= 0;
}
if(totalHour>=15) {
System.out.println("You cant work more than 15 hours a day");
}
if(totalHour<0) {
salary=Math.abs(totalHour)*paymentPerHour;
}
}
System.out.println("You've been working for: "+totalHour+" Hours"+",And your payment is: "+salary);
}
}

You should not use continue; in the loop. It will force the loop to go to the next iteration even if the conditions are met. Instead you should use break; which will terminate the loop if the conditions are met. Also you should not add the condition paymentPerHour>0 because it will skip the loop if the user enters a negative number (thx to Idle_Mind for this one). See the code sample:
while(true)
{
if(paymentPerHour>=28 &&paymentPerHour<=100) {
break; // This will terminate the loop if the conditions are met
}
// This part will only run if the conditions are not met
System.out.println("Please enter payment per hour");
paymentPerHour=in.nextInt();
}

Related

Created a two condition While loop, one condition works as should the other causes an infinite loop

so im still new to java programming and for this program i need to make a program that calculates change for a vending machine. It is based of a 5 cent increment between a value of 25 cents to a dollar. for this assignment if i use a loop to force the user to input a value in bounds i get extra credit, since i originally was going to scratch because i wasnt getting it but soon did im back to using it. only thing is for one of my conditions it creates an infinite loop of the output message and im not sure why. any advice would be appreciated
/** Carmine A
The purpose of this program is to calculate the change to be dispensed from
a vending machine */
//import scanner so user can input data
import java.util.Scanner;
public class lab2Test{
//declaration of variables to be used in program
float changeGiven;
public static void main(String args[]) {
//ties user input variable to class so scanner can use it
int userInput;
int itemCost;
//initiates the keyboard to be used
Scanner keyboard = new Scanner(System.in);
//print statement to tell user how to enter price
System.out.println("Enter price of item from 25 cents to a dollar in 5-cent increments \n"
+ "Do not enter a decimal point");
//user inputs value to be set to variable
userInput= keyboard.nextInt();
//System.out.println("You entered ." +userInput + " as the price");
//while loop to make sure input stays in bounds
while(userInput<25 || userInput>100){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
while(userInput>25 && userInput<100){
System.out.println("Price is in bounds");
System.out.println("Please enter a valid amount between 25-100");
itemCost=keyboard.nextInt();
}
}
itemCost=userInput;
//print out item cost based off users input
System.out.println("You enetered: " + itemCost +" as the items cost");
}
}
update
ok took what you guys said and made this
//while loop to make sure input stays in bounds
while(userInput<25 || userInput>100){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
userInput=keyboard.nextInt();
}
thanks for the help! knew it was something dumb, but this is why i ask for help so i can learn
so i believe it is frowned upon if i made another thread for the same program so i will add to this one.
i have completed just about everything i need but am having a few issues.
1. for some reason after i compile and run my code "Change Due:" prints twice, i am unsure why since i only have it once in a print statement but i can be missing it.
2.i need to print out in a money format and for some reason i have tried different formatting options and none will round (i have a feeling it is but it is not displaying because of the second "Change due:" printing) but can be wrong
3. on line 55 i am receiving this message and not sure why C:\Users\finst\Desktop\Intro to Java\Labs\Lab2\lab2Test.java:55: error: incompatible types: possible lossy conversion from double to int
changeRemainder= (changeDue*(double)100);
this is what i currently have:
/** Carmine
The purpose of this program is to calculate the change to be dispensed from
a vending machine */
//import scanner so user can input data
import java.util.Scanner;
public class lab2Test{
//declaration of variables to be used in program
public static void main(String args[]) {
//ties user input variable to class so scanner can use it
double userInput;
double itemCost;
//initiates the keyboard to be used
Scanner keyboard = new Scanner(System.in);
//print statement to tell user how to enter price
System.out.println("Enter price of item from 25 cents to a dollar in
5-cent increments");
//user inputs value to be set to variable
userInput= keyboard.nextDouble();
//while loop to make sure input stays in bounds
while(userInput<(.25) || userInput>(1.00)){
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1
dollar");
userInput=keyboard.nextDouble();
}
//print out item cost based off users input
System.out.println("You entered: " + userInput +" as the items cost");
System.out.println("You entered a dollar to pay with");
//algorithm to calculate change due
int quarters;
int nickels;
int dimes;
int pennies;
int changeRemainder;
double changeDue;
double dollar=1;
//calculates change due
changeDue= (dollar - userInput);
//System.out.printf("%.2f" + "\n" ,changeDue);
//System.out.println("Change due:" + changeDue);
//makes the remainder into a number that can be used
changeRemainder= (changeDue*(double)100);
//calculates the amount of each coin needed to make the change
quarters= (changeRemainder / 25);
changeRemainder= changeRemainder % 25;
dimes= (changeRemainder/10);
changeRemainder= changeRemainder%10;
nickels=(changeRemainder/5);
changeRemainder= changeRemainder%5;
pennies=(changeRemainder);
//output statement to print coin amounts
System.out.println("Quarters: " + quarters);
System.out.println("Dimes: " + dimes);
System.out.println("Nickels: " + nickels);
System.out.println("Pennies: " + pennies);
}
}
As userInput is never updated in the loop then its value does not change and it will potentially loop for ever.
Maybe you mean userInput=keyboard.nextInt(); but you do not need two loops anyway.
userInput=keyboard.nextInt();
while (userInput<25 || userInput>100) {
System.out.println("Invalid amount entered! \n"
+ "Please enter an amount between 25 cents and 1 dollar");
userInput=keyboard.nextInt();
}
You don't need 2 while loops; just one will do. In any case, your while loop checks the 'userInput' variable, but that never changes in the while loop; you are updating the itemCost variable instead.
I would use a Boolean for your while loop, and create an if else statement within this to check for valid entry and calculate the change. Hope this helps!
boolean end = true;
while (end) {
//retrieve user input of cost and assign value to variable
//create an if statement check if the value is valid
if(itemCost >=25 && itemCost <=100){
//retrieve user input for change entered
//calculate change for the user and display it
//end loop
end = false;
} else {
//invalid entry
end = false;
}
}

java: loop with switch only works sometimes

I'm really scratching my heard on this one. I'm new at java, and I'm having the strangest thing happen.
It's homework and I'm taking it one step at a time. My issue is the loop just keeps going and stops asking for input, just keeps looping until it terminates. My comments are largely for myself. I tried to extract what was causing my problem and post it here.
Look at the "hatColor" switch, you'll notice the way I'm making sure the user enter only from the options I have allotted. Should I be using a exception handler or something?
Anyway, in short, the problem is that if I enter something with spaces, the loop skips asking for my next input. Like, if I entered "y y y y y " to the scanner when first prompted, the program will terminate and not give me the chance to enter something else.
Please, anyone that understands this, I would really appreciate your help.
import java.util.Scanner;
public class Testing
{
static String hatColor;
public static void main(String[] args) {
gameStart();
}
public static void gameStart()
{
Scanner userInput = new Scanner(System.in);
boolean keepLooping = true;
int loopCounter = 0;
System.out.println("The game begins. You must choose between 3 different colored hats."
+ " You can type white, black, or gray.");
while (keepLooping == true)
{
hatColor = userInput.next();
switch(hatColor)
{
case "white":
System.out.println("You have chosen the path of well intentioned decisions.");
walletDrop();
//the two items below are only there in case the wallet drop somehow completes without calling another method
keepLooping = false; // stops the while loop from looping again.
break; // breaks out of the switch
case "gray":
System.out.println("You have chosen the path of free will.");
walletDrop();
keepLooping = false;
break;
case "black" :
System.out.println("You have chosen the path of personal gain.");
walletDrop();
keepLooping = false;
break;
default : //we could just copy this default chunk for later switch statements
if (loopCounter >= 3)//end program on them
{
System.exit(0);
}
System.out.println("You didn't enter a usable answer. Try again");
loopCounter++;
if (loopCounter == 3)
{
System.out.println("This program will self destruct if you enter another invalid response.");
}
}//end of switch
}//end of while
}//end of game start method
public static void walletDrop()
{
System.out.println("wallet drop successful");
}
}
So I have actually solved this right after posting. In case someone else needs to look here for help:
The issue I was experiencing was due to using the scanner method
variableToAssign = scannerName.next();
instead of
variableToAssign = scannerName.nextLine();

How do I keep track of the balance on a bank account?

I am going to create a program that keeps track of the balance on a bank account. The program shall use a loop that continues until the user choses to exit by answering no to the question Do you want to continue?.
In the loop the user shall be asked to enter an amount (positive for deposit and negative for withdraw). The amount shall be added/subtracted from an account balance variable. All deposits/withdraws shall be saved as a history so that we can print it later. When the user choses to exit the loop the current account balance together with the account history (from the array/ArrayList) shall be printed.
Now, I want to use an array with ten slots for the history feature.
My question is how can I keep track of the all deposit, withdraw and current account balance (using an array with ten slots for the history feature) so that I can print it out while the user exits the program?
My code:
BankApp class:
package bankapp;
import java.util.Scanner;
public class BankApp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
askingUser au = new askingUser();
System.out.println("WELCOME TO OUR BANK!\nYou have 100 SEK by default in your account.");
while (true) {
au.userInput();
System.out.println("Do you want to continue? Answer by Yes or No.");
String yesOrNo = input.next();
if (yesOrNo.equalsIgnoreCase("yes")) {
au.userInput();
} else if (yesOrNo.equalsIgnoreCase("no")) {
System.out.println("History: ");
//print out the transaction history
System.exit(0);
} else {
System.out.println("Invalid character input.");
}
}
}
}
askingUser class:
package bankapp;
import java.util.Scanner;
public class askingUser {
Scanner input = new Scanner(System.in);
double initialBal = 100;
public void userInput() {
System.out.println("Enter your amount: (+ve for deposit & -ve for withdraw)");
double inputAmount = input.nextDouble();
if (inputAmount >= 0) {
double newPosAm = initialBal + inputAmount;
System.out.println("Your current balance is: " + newPosAm + " SEK");
} else {
double newNegAm = initialBal + inputAmount;
System.out.println("Your current balace is: " + newNegAm + " SEK");
}
}
}
If you use an array, you have to keep track of the number of elements stored inside and resize the array when necessary. The easiest way would be to keep the history as strings in ArrayList. You would add one message to that list per transaction:
ArrayList<String> history = new ArrayList<String>();
void addToHistory(String transaction) {
history.add(transaction);
}
void printHistory() {
for(String s : history) {
System.out.println(s);
}
}
addToHistory("Withdrawal: 100 SEK" );
addToHistory("Deposit: 200 SEK" );
printHistory();
You need a queue to do that. However, for a simple, fast and primitive implementation you can:
Define an object called Transaction(deposit - double, withdraw - double, current account balance - double)
Add a List of Transactions into askingUser class as an attribute. I strongly recommend renaming the class name to AskingUser to make it seen as object.
At each operation add a new Transaction to end of the List you just added.
At exit, print out the last -say- 10 elements of the List; you can reach it through askingUser object. You can also define a function in askingUser class to print out the last 10 elements, if you make the function work according to selected number of elements, you can add number of Transactions to the function's inputs.

while loop incriment causing different results based on where the increment expression in placed

Ok.. i made this wile loop in main---
public static void main(String[] args){
int age=0;
outer:
while (age<21) {
age++;
if(age==16){
System.out.println("Get your licence");
continue outer;
}
System.out.println("Another year");
}
}
This produces the desired result--
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Another year
Get your licence
Another year
Another year
Another year
Another year Another year
but if i shift the incrementer to the last line in the for loop.. something unexpected happens ..... IT LEADS TO AN INFINITE LOOP
public static void main(String[] args){
int age=0;
outer:
while (age<21) {
if(age==16){
System.out.println("Get your licence");
continue outer;
}
System.out.println("Another year");
age++;
}
}
Results in...
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence
Get your licence.... till infinity
What is the reason for this behavior?
When you reach this point:
continue outer;
You return to the start of the loop, without incrementing age and therefore you are going inside this condition (age == 16) over and over again.
The problem is that you're continuing before you increment, so you stay 16 forever (hmmm, trying to decide whether that would be cool or hell...). There's nothing in a while loop that automatically increments the loop variable.
If you want a loop that always includes an increment, even when you continue, consider a for loop which would be a better choice for this situation in any case:
public static void main(String[] args){
int age;
for (age = 0; age < 21; ++age) {
if(age==16){
System.out.println("Get your licence");
continue;
}
System.out.println("Another year");
}
}
(I hope I got your bracing style right there; it's quite alien to me...)
...and separately, where possible it's best to avoid continue (although it definitely has good uses). In this case, a simple else would be a better choice:
public static void main(String[] args){
int age;
for (age = 0; age < 21; ++age) {
if(age==16){
System.out.println("Get your licence");
}
else {
System.out.println("Another year");
}
}
}
(Again, apologies if I didn't quite get the bracing style right...)

Ending a for loop by pressing 'q'

I have been doing a project for my java class. For the project I have to have the user enter input and calculate their body mass index and body surface area the program is supposed to remain running until the user enters a "q". I cannot get my program to stop running when a "q" is put in it just crashes. Also I am very new to java and programming in general so I would appreciate any help. My code is as follows.
Thanks : )
public static void main(String[] args) {
//Scanner
Scanner stdIn = new Scanner(System.in);
//Variables
final double METERS_TO_CM = 100; // The constant to convert meters to centimeters
final double BSA_CONSTANT = 3600; // The constant to divide by for bsa
double bmi; // Body Mass Index
String weight; // Weight in kilograms
String height; // Height in meters
String classification; // Classifies the user into BMI categories
double bsa; // Body surface area
do {
System.out.print("Welcome to the BMI and BSA Calculator to begin enter weight in kilograms.");
weight = stdIn.next();
System.out.print("Enter height in meters: ");
height = stdIn.next();
double height2 = Double.parseDouble(height);
double weight2 = Double.parseDouble(weight);
bmi = weight2/(height2*height2);
if (bmi < 18.5)
{
classification = "Underweight";
}
else if (bmi < 25)
{
classification = "Normal";
}
else if (bmi < 30)
{
classification = "Overweight";
}
else
{
classification = "Obese";
}
System.out.println("Your classification is: " + classification);
bsa = Math.sqrt(((height2*METERS_TO_CM)*weight2)/BSA_CONSTANT);
System.out.printf("BMI: %.1f\n", bmi);
System.out.printf("BSA: %.2f\n", bsa);
System.out.println("Hit 'q' to quit");
} while (stdIn.nextLine().compareToIgnoreCase("q")==0);
}
}
I would guess that your "q" input is written in weight and therefore you try to parse it to a Double, which throws an unhandled Exception and stops the execution.
You should handle this Exception and make the system break the while loop when triggering it.
You're grabbing the entire line for your while loop condition.
Try just grabbing the next() instead of nextLine().
Also, you're looking at while it DOES equal 0 ... meaning equal. I'd change that to != instead. You want to continue looping while the next token is NOT Q.
Let's make a structural change to make this easier for you to do.
We are going to change it so that your do-while loop always is running, until you explicitly tell it to stop.
Your current while is:
while(stdIn.nextLine().compareToIgnoreCase("q")==0);
Which works ok, but we have a more simple way to do this. Have you heard of the break statement?
I would suggest you use break. This statement will 'break' you out of the while loop; basically it tells the program to stop looping when it is called. This will be a bit easier to follow than your somewhat confusing do-while.
do {
//Your Do code goes here, as before
...
//
//Your newly added break statement will go here.
//This breaks out of the while loop when your inputed 'choice' value is
//equal to the string of "q" (for quit)
if (Choice.equals("q"))){
break;
//When break is called nothing else in the loop will run
}
//Same thing but with the string of "quit"
if (Choice.equals("quit"){
break;
}
}while (true);
//Your new while statement is simply while(true) which will run until break is called
Hopefully that is helpful to you.
Don't actually use a loop. Since it's impractical someone would ever max the call stack out by answering too many questions, just make the whole operation a function. At the end of the function, call itself if the result isn't Q.
its simple use this
while (true)
{
Console.WriteLine("Start processing");
//processing code here
Console.WriteLine("finish processing");
Console.WriteLine("start again? y/n?");
if (Console.ReadLine().Equals("n"))
break;
}

Categories