I'm trying to write a program that uses scanner keyboard to input these values and uses a loop to have them increase (2006-2010, year-year, & an increase in price, 90-100, etc.)
The output is supposed to look like this:
Enter the current Mars bar price in cents: 90
Enter the expected yearly price increase: 15
Enter the start year: 2006
Enter the end year: 2010
Price in 2006: 90 cents
Price in 2007: 105 cents
Price in 2008: 120 cents
Price in 2009: 135 cents
Price in 2010: 150 cents
This is the code I have so far:
import java.util.Scanner;
public class Problem_2 {
public static void main(String[] args) {
// TODO, add your application code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the current Mars bar price in cents: ");
int m = keyboard.nextInt();
System.out.print("Enter the expected yearly price increase: ");
int p = keyboard.nextInt();
int a = m+p;
int count = 1;
System.out.print("Enter the start year: ");
int start = keyboard.nextInt();
System.out.print("Enter the end year: ");
int end = keyboard.nextInt();
for (int i = start; i <= end; i++){
System.out.print("Price in " +i+ ": " +m);start++;
}
}
and it allows me to have the year increasing to the set amount (again like 2006-2010) but I'm stuck on having the price increase along with it by the set amount, I assume it would be a nested loop but I'm not sure how to write it.
(I assume a nested loop because that's what we're learning right now.)
If anyone has any advice on what I could write, I'd really appreciate it!
I think you just need to sum the expected yearly price increase to the current price in each iteration of your loop, it'd be something like this:
import java.util.Scanner;
public class Problem_2 {
public static void main(String[] args) {
// TODO, add your application code
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the current Mars bar price in cents: ");
int m = keyboard.nextInt();
System.out.print("Enter the expected yearly price increase: ");
int p = keyboard.nextInt();
int count = 1;
System.out.print("Enter the start year: ");
int start = keyboard.nextInt();
System.out.print("Enter the end year: ");
int end = keyboard.nextInt();
for (int i = start; i <= end; i++){
System.out.print("Price in " +i+ ": " +m);
m += p; // sum expected price for each iteration
}
}
Related
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter your salary per hour: ");
int salary = input.nextInt();
System.out.print("Enter number of hours: ");
int hours = input.nextInt();
int sum = salary * hours;
if (hours == 0) {
System.out.println("Stop!");
break;
}
System.out.println("Total salary " + sum);
}
}}
I want to be able to enter numbers until I press 0, and then I want the program to stop. It stops after two zeros, but how can I make it stop after pressing only one zero? I have tried this while-if loop and different do-while loops, I just can't make it work.
Your code does exactly what you tell it to do.
You tell it to:
first ask for TWO numbers
to then compare the first number, and stop on 0
So, the solution is:
ask for one number
compare the number, stop on 0
ask for the second number
If you want to exit whenever you type 0, then you have to check every value after its input.
There is the code example:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("What's your salary per hour? ");
int salary = scanner.nextInt();
if (salary == 0)
exit();
System.out.print("How many hours did you worked today? ");
int hours = scanner.nextInt();
if (hours == 0)
exit();
int sum = salary * hours;
System.out.println("Your total salary is " + sum);
}
}
private static void exit() {
System.out.println("Have a nice day!");
System.exit(0);
}
Please write a comment if that doesn't match your expectation
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.
So I have everything working except that once I enter the input required I get input like this:
1 5.0
2 6.0
3 7.0
4 8.0
I don't know what I'm doing wrong as it seems its not increasing in the right increments based on the growthRate that I input which was 50. Also can't get the organism number to increase according to the following day. Any suggestions?
//Purpose of program to predict population of organisms
import java.util.Scanner;
public class Population {
public static void main(String[] args) {
double growthRate = -1;
int population = 0;
int days = -1;
double popResult = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("\nEnter the starting number of organisms:");
population = keyboard.nextInt();
while (population < 2) {
System.out.println("\nError!! Please re-enter number of organisms.");
population = keyboard.nextInt();
}
System.out.println("\nEnter rate of growth as percentage:");
growthRate = keyboard.nextInt() / 100;
while (growthRate < 0) {
System.out.println("\nError!! Growth rate must be a positive number. Please re-enter.");
growthRate = keyboard.nextInt();
}
System.out.println("\nEnter number of days organisms will grow:");
days = keyboard.nextInt();
while (days < 0) {
System.out.println("\nError!! Number of days cannot be less than 1. Please re-enter.");
days = keyboard.nextInt();
}
System.out.println("Days" + "\t" + "Organisms");
System.out.println("------------------");
popResult = population;
growthRate = growthRate / 100;
for (int numberOfDays = 1; numberOfDays < days; numberOfDays++) {
System.out.println(numberOfDays + "\t" + popResult);
popResult = (popResult * growthRate) + popResult;
}
}
}
You are taking input for growthRate as Integer format in line
growthRate=keyboard.nextInt()/100;
If it is less than 0 then you take input without dividing by 100 as
growthRate=keyboard.nextInt();
and finally you are again dividing growthRate as
growthRate=growthRate/100;
So you have to take input outside the while loop only as
growthRate=keyboard.nextInt();
Modified code
import java.util.Scanner;
public class Population
{
public static void main(String[] args)
{
double growthRate=-1;
int population=0;
int days=-1;
double popResult=0;
Scanner keyboard=new Scanner(System.in);
System.out.println("\nEnter the starting number of organisms:");
population=keyboard.nextInt();
while(population<2)
{
System.out.println("\nError!! Please re-enter number of organisms.");
population=keyboard.nextInt();
}
System.out.println("\nEnter rate of growth as percentage:");
growthRate=keyboard.nextInt();
while(growthRate<0)
{
System.out.println("\nError!! Growth rate must be a positive number. Please re-enter.");
growthRate=keyboard.nextInt();
}
System.out.println("\nEnter number of days organisms will grow:");
days=keyboard.nextInt();
while(days<0)
{
System.out.println("\nError!! Number of days cannot be less than 1. Please re-enter.");
days=keyboard.nextInt();
}
System.out.println("Days" + "\t" + "Organisms");
System.out.println("------------------");
popResult=population;
growthRate=growthRate/100;
for(int numberOfDays=1; numberOfDays<days; numberOfDays++)
{
System.out.println(numberOfDays + "\t" + popResult);
popResult=(popResult * growthRate) + popResult;
}}}
This question already has answers here:
Division in Java always results in zero (0)? [duplicate]
(3 answers)
Closed 8 years ago.
This is my first CS project ever. After creating my method, I ran the code to see if it works so far, everything works correctly but it does not actually do the math inside the method. Been working on this forever and can't find the bug. Any help would be great. Its due tomorrow lol.
public static void main(String[] args) {
int numberOfStudents = 0;
int total = 0;
int value = 0;
int creditHours;
double tuition;
int classesMissed;
System.out.println("Tuition Wasted Based on Student Absences and its effect on GPA.");
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the number of students to consider: ");
value = keyboard.nextInt();
while (value >= 5)
{
if (value > 5)
System.out.println("Number of students must be between 1 and 5");
System.out.print("Please re-enter a value number of students to consider: ");
value = keyboard.nextInt();
}
System.out.print("Enter the student ID for student 1: ");
value = keyboard.nextInt();
System.out.print("For how many credit hours is the student registered: ");
creditHours = keyboard.nextInt();
System.out.print("Enter the amount of the tuition for the semester: ");
tuition = keyboard.nextDouble();
System.out.print("Enter the average number of classes the student misses in a week: ");
classesMissed = keyboard.nextInt();
while (classesMissed > creditHours)
{
if (classesMissed > creditHours)
System.out.print("That is not possible, please re-enter the number of classes missed in a week: ");
classesMissed = keyboard.nextInt();
}
DetermineWastedTuition(creditHours, tuition, classesMissed);
}
public static void DetermineWastedTuition(int creditHours, double tuition, int classesMissed){
double weeklyTuition;
weeklyTuition = tuition / 10;
double weeklyTuitionWasted;
weeklyTuitionWasted = weeklyTuition *(classesMissed / creditHours);
double semesterWasted;
semesterWasted = weeklyTuitionWasted * 16;
System.out.println("Tuition money wasted each week is " + weeklyTuitionWasted);
System.out.println("Tuition money wasted each semester is " + semesterWasted);
}
With the sample output as:
Tuition Wasted Based on Student Absences and its effect on GPA.
Enter the number of students to consider: 1
Enter the student ID for student 1: 1234555
For how many credit hours is the student registered: 15
Enter the amount of the tuition for the semester: 7500
Enter the average number of classes the student misses in a week: 2
Tuition money wasted each week is 0.0
Tuition money wasted each semester is 0.0
The following calculation :
weeklyTuitionWasted = weeklyTuition * (classesMissed / creditHours);
would return 0.0 if classesMissed < creditHours, since you are dividing two int variables, and therefore the result will be an int.
Change it to :
weeklyTuitionWasted = weeklyTuition * ((double) classesMissed / creditHours);
I'm doing a homework assignment in my Java class. I got most of it except for this one part about elapsed time. We have to use methods. Here's the assignment and the code I have.
"You have just been hired by a company to do it’s weekly payroll. One of the functions you must perform daily is to check the employee time cards and compute the elapsed time between the time they “punch in” and “punch out”. You also have to sometimes convert hours to minutes, days to hours, minutes to hours and hours to days. Since you’ve just finished your first programming class you decide to write a program that will help you do your job.
You decide to structure your program the following way. The main function will just be a menu that the user can select from to get the information they want. Each option on the menu will call a specific method(s) to solve the task and/or output the answer.
You may assume for this program that all elapsed times will be in a single day but the others may span much further. Be sure to provide sufficient test data to demonstrate that your solutions are correct. (show at least one output for each conversion [probably several for option #5]). "
import java.util.*;
public class Prog671A
{
public static void hoursToMinutes()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter hour(s): ");
int hours = input.nextInt();
System.out.println(hours + " * 60 = " + (hours * 60) + " minutes.");
System.out.println("");
}
public static void daysToHours()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter day(s): ");
int days = input.nextInt();
System.out.println(days + " * 24 = " + (days * 24) + " hours.");
System.out.println("");
}
public static void minutesToHours()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter minute(s): ");
int minutes = input.nextInt();
System.out.println(minutes + " / 60 = " + ((double)minutes / 60) + " hours.");
System.out.println("");
}
public static void hoursToDays()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter hour(s): ");
int hours = input.nextInt();
System.out.println(hours + " / 24 = " + ((double)hours / 24) + " days.");
System.out.println("");
}
public static void elapsedTime()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter the beginning hour: ");
int startingHour = input.nextInt();
System.out.print("Enter the beginning minute(s): ");
int startingMinutes = input.nextInt();
System.out.print("Enter AM/PM: ");
String startingAmOrPm = input.nextLine();
System.out.print("Enter the ending hour: ");
int endingHour = input.nextInt();
System.out.print("Enter the ending minute(s): ");
int endingMinutes = input.nextInt();
System.out.print("Enter AM/PM: ");
String endingAmOrPm = input.nextLine();
System.out.println("");
System.out.println("The elapsed time is: " + );
}
public static void main (String args [])
{
int x = 1;
while (x == 1) {
Scanner input = new Scanner (System.in);
System.out.println("Conversion Tasks");
System.out.println("\t1. Hours -> Minutes");
System.out.println("\t2. Days -> Hours");
System.out.println("\t3. Minutes -> Hours");
System.out.println("\t4. Hours -> Days");
System.out.println("\t5. Elapsed time between two times");
System.out.println("\t6. Exit");
System.out.print("Enter a number: ");
int menu = input.nextInt();
System.out.println("");
if (menu == 1)
hoursToMinutes();
if (menu == 2)
daysToHours();
if (menu == 3)
minutesToHours();
if (menu == 4)
hoursToDays();
if (menu == 5)
elapsedTime();
if (menu == 6)
x = 0;
}
}
}
I just need help here
public static void elapsedTime()
{
Scanner input = new Scanner (System.in);
System.out.print("Enter the beginning hour: ");
int startingHour = input.nextInt();
System.out.print("Enter the beginning minute(s): ");
int startingMinutes = input.nextInt();
System.out.print("Enter AM/PM: ");
String startingAmOrPm = input.nextLine();
System.out.print("Enter the ending hour: ");
int endingHour = input.nextInt();
System.out.print("Enter the ending minute(s): ");
int endingMinutes = input.nextInt();
System.out.print("Enter AM/PM: ");
String endingAmOrPm = input.nextLine();
System.out.println("");
System.out.println("The elapsed time is: " + );
}
Just convert the start and end times to minutes since the start of the day (at midnight). For p.m., just add 12 to the hour before converting to minutes. Then subtract and convert back to hours and minutes for the elapsed time.
why do you want to take the hours etc stuff manually??
Read the system date when the User logs in System.currentTimeMillis() store this time somewhere
When the User exists do the same get the System Time. Subtract it from the time you stored initially when the user logged in.
I hope this is what ur looking for ?