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 ?
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
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
}
}
This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 5 years ago.
I have fixed the errors in my original code and formatted it correctly. However, the code is now repeating String next() before it proceeds to the last method. I thought I understood why, but when I tried to fix it, the program failed again. Thank you for your time!
import java.util.Scanner;
public class LearnScanner {
public static void main (String[] args) {
first();
next();
third();
}
public static void first() {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Vacation Planner!!");
System.out.print("What is your name?");
String name = input.nextLine();
System.out.print("Nice to meet you " + name + ", where are you travelling to?");
String destination = input.nextLine();
System.out.println("Great! "+destination +" sounds like a great trip");
}
public static String next() {
Scanner input = new Scanner(System.in);
System.out.print("How many days are you going to spend travelling?");
String days = input.nextLine();
System.out.print("How much money in USD are you planning to spend on your trip?");
String budget = input.nextLine();
System.out.print("What is the three letter currency symbol for your travel destination?");
String currency = input.nextLine();
System.out.print("How many " + currency + " are there in 1 USD?");
String currencyConversion = input.nextLine();
return days;
}
public static void third() {
int days = Integer.valueOf(next());
int hours = days * 24;
int minutes = hours * 60;
System.out.println("If your are travelling for " + days + " days that is the same as " + hours + " hours or " + minutes + " minutes");
}
}
From what I see, the method next() gets called once from the main method, and then gets called again in third at
int days = Integer.valueOf(next());
Maybe you should create an instance variable called days and store the value of next() in it. Then use the value of the variable in the third() method. i.e.
import java.util.Scanner;
public class LearnScanner {
private static int days = 0;
public static void main (String[] args) {
first();
days = Integer.parseInt(next());
third();
}
public static void first() {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to Vacation Planner!!");
System.out.print("What is your name?");
String name = input.nextLine();
System.out.print("Nice to meet you " + name + ", where are you travelling to?");
String destination = input.nextLine();
System.out.println("Great! "+destination +" sounds like a great trip");
}
public static String next() {
Scanner input = new Scanner(System.in);
System.out.print("How many days are you going to spend travelling?");
String days = input.nextLine();
System.out.print("How much money in USD are you planning to spend on your trip?");
String budget = input.nextLine();
System.out.print("What is the three letter currency symbol for your travel destination?");
String currency = input.nextLine();
System.out.print("How many " + currency + " are there in 1 USD?");
String currencyConversion = input.nextLine();
return days;
}
public static void third() {
int tempDays = Integer.valueOf(days);
int hours = days * 24;
int minutes = hours * 60;
System.out.println("If your are travelling for " + tempDays + " days that is the same as " + hours + " hours or " + minutes + " minutes");
}
Trying to figure out how to get my program to restrict the input of a integer less then 1 and also restrict input of strings in the scanner. Here's my code:
import java.util.Scanner; // Import scanner object
import java.io.*; // Import for file and IOException
public class Distance {
public static void main(String[] args) throws IOException {
int distance;
int speed, time;
String filename;
System.out.println("Welcome to Distance Calculator.");
// Create a scanner keyboard for user input
Scanner keyboard = new Scanner(System.in);
// Vehicle speed
System.out.print("Vehicle speed (MPH): ");
speed = keyboard.nextInt();
while (!keyboard.hasNextInt()) {
System.out.print("Please enter a valid #: ");
speed = keyboard.nextInt();
if (speed < 1) {
System.out.print("Please enter a # greater then 1: ");
keyboard.nextInt();
}
}
System.out.print("Time vehicle traveled (HR): ");
while (!keyboard.hasNextInt()) {
time = keyboard.nextInt();
if (time < 1) {
System.out.print("Please enter a valid time: ");
speed = keyboard.nextInt();
}
}
time = keyboard.nextInt();
keyboard.nextLine(); // Consume next line
// Get filename
System.out.print("File name for saving: ");
filename = keyboard.nextLine();
// Open file
String filePath = "C:/Users/Nik/Desktop/";
PrintWriter outputFile = new PrintWriter(filePath + filename);
outputFile.println("Hour Distance Traveled");
outputFile.println("-----------------------------");
for (int hour = 1; hour <= time; hour++) {
distance = (speed * hour);
outputFile.println(hour + "\t\t\t" + (distance + " Mi"));
}
outputFile.close();
System.out.print("Date written to " + filePath + filename);
}
}
Would really appreciate the assistance.
Well I believe that changing the "whiles" a bit like this might work like you want it to. It takes care of both the input problem when you insert something that's not an integer and the positive integer problem when a non positive integer is inserted. I tested it and I think it worked how it's supposed to. Try it out.
public static void main(String[] args) throws IOException{
int distance;
int speed, time;
String filename;
System.out.println("Welcome to Distance Calculator.");
// Create a scanner keyboard for user input
Scanner keyboard = new Scanner(System.in);
// Vehicle speed
System.out.print("Vehicle speed (MPH): ");
while (!keyboard.hasNextInt() ||
((speed = keyboard.nextInt()) < 1) ) {
System.out.print("Please enter a valid #: ");
keyboard.nextLine();
}
System.out.print("Time vehicle traveled (HR): ");
while (!keyboard.hasNextInt() ||
((time = keyboard.nextInt()) < 1) ) {
System.out.print("Please enter a valid #: ");
keyboard.nextLine();
}
keyboard.nextLine(); // Consume next line
// Get filename
System.out.print("File name for saving: ");
filename = keyboard.nextLine();
// Open file
String filePath = "C:/Users/Nik/Desktop/";
PrintWriter outputFile = new PrintWriter(filePath + filename);
outputFile.println("Hour Distance Traveled");
outputFile.println("-----------------------------");
for (int hour = 1; hour <= time; hour++) {
distance = (speed * hour);
outputFile.println(hour + "\t\t\t" + (distance + " Mi"));
}
outputFile.close();
System.out.print("Date written to " + filePath + filename);
}
I think this should work:
System.out.print("Vehicle speed (MPH): ");
speed = -1;
do {
System.out.println("Please enter a valid integer greater than 1");
if (keyboard.hasNextInt() {
speed = keyboard.nextInt();
}
} while (speed < 1)
I'm pretty sure the problem is coming from the ! in your while loop, however I think I have managed to clean up the code.
Disclaimer: I have not tested this code to see if it works, however I thought I would give it a shot, hope it helps.
My final code:
int distance;
int speed = 0, time;
String filename;
boolean validInput = false; // Boolean for validating scanner input
System.out.println("Welcome to Distance Calculator.");
// Create a scanner keyboard for user input
Scanner keyboard = new Scanner(System.in);
// Vehicle speed
System.out.print("Vehicle speed (MPH): ");
// Method for validating user input
while (validInput == false) {
if (!keyboard.hasNextInt()) { // check if keyboard scanner !integer
System.out.print("Please enter a valid #: "); // prompts user for valid input
keyboard.nextLine(); // consumes next line
}
else {
speed = keyboard.nextInt();
if (speed < 1) { // validates if speed > 0
System.out.print("Please enter a value greater then 1: "); // prompts user for valid speed
keyboard.nextLine(); // consumes next line
}
else validInput = true; // if statements are passed then set bool to True and end loop
}
}
I'm having an issue with the code below. It's all working fine, except I want the program to restart if the user types in "Y" at the end, and end if anything else is pressed.
However, whenever I type anything at the "Restart Calculator" prompt, it will stop running, regardless of whether I type in "Y" or "N". Validation with the Y/N is not too important here, I just want it to restart if Y is typed and end if anything else is typed.
Apologies for the noob code, Java beginner here.
import java.util.Scanner;
import java.text.*;
public class Savings {
public static void main(String[] args)
{
//Imports scanner, to read user's input
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
do {
//Asks for and receives user's initial deposit
int initial_Deposit;
do {
System.out.print("Enter initial deposit in dollars (Between $1 - $50000: ");
while (!scan.hasNextInt()) {
System.out.println("Please enter a valid number between '1-50000'");
scan.next();
}
initial_Deposit = scan.nextInt();
} while (initial_Deposit <= 0 || initial_Deposit >= 50001);
//Asks for and receives user's interest rate
double interest_Rate;
do {
System.out.print("Enter interest rate as a percentage between '0.1-100.0' (e.g. 4.0):");
while (!scan.hasNextDouble()) {
System.out.println("Enter interest rate as a percentage between '0.1-100.0' (e.g. 4.0):");
scan.next();
}
interest_Rate = scan.nextDouble();
} while (interest_Rate <= 0.0 || interest_Rate >= 100.1);
//Asks for and receives user's monthly deposit
int monthly_Deposit;
do {
System.out.print("Enter monthly deposit in dollars between '$1 - $5000: ");
while (!scan.hasNextDouble()) {
System.out.println("Enter monthly deposit in dollars between '$1 - $5000: ");
scan.next();
}
monthly_Deposit = scan.nextInt();
} while (monthly_Deposit <= 0 || monthly_Deposit >= 5001);
//Asks for and receives user's investment duration
int monthly_Duration;
do {
System.out.print("Enter investment duration (Between 1 and 12): ");
while (!scan.hasNextDouble()) {
System.out.println("Enter investment duration (Between 1 and 12): ");
scan.next();
}
monthly_Duration = scan.nextInt();
} while (monthly_Duration <= 0 || monthly_Duration >= 13);
//Asks for and receives user's first name
String first_Name;
System.out.print("Enter first name: ");
first_Name = input.next();
//Asks for and receives user's surname
String last_Name;
System.out.print("Enter surname: ");
last_Name = input.next();
//Formats first name to only first letter
char firstLetter = first_Name.charAt(0);
//Changes name to correct format
String formatted_Name;
formatted_Name = "Savings growth over the next six months for " + last_Name + ", " + firstLetter;
System.out.println(formatted_Name);
//Calculates the first balance
double balanceCurrent;
balanceCurrent = initial_Deposit + monthly_Deposit;
//Prepares to format currency
DecimalFormat df = new DecimalFormat("#.##");
//Defining variables
double balanceNew;
double interestEarned;
//Defining counter for while loop
int counter;
counter = monthly_Duration;
int month_Counter;
month_Counter = 1;
//While loop to calculate savings
while (counter > 0) {
balanceNew = balanceCurrent + (balanceCurrent *((interest_Rate /12)/100));
interestEarned = balanceCurrent *((interest_Rate /12)/100);
balanceCurrent = balanceNew + monthly_Deposit;
System.out.println("Balance after month " + month_Counter + ": $" + df.format((balanceNew)));
System.out.println("Interest earned for this month: $" + df.format(interestEarned));
counter = counter - 1;
month_Counter = month_Counter + 1;
}
//Formats data into a table
balanceCurrent = initial_Deposit + monthly_Deposit;
counter = monthly_Duration;
int month;
month = 0;
String dollarSign = "$";
String stringHeadingOne = "Month";
String stringHeadingTwo = "New Balance";
String stringHeadingThree = "Interest Earned";
String dividerOne = "----- ----------- ---------------";
System.out.println("");
System.out.printf("%-9s %s %19s \n", stringHeadingOne, stringHeadingTwo, stringHeadingThree);
System.out.println(dividerOne);
while (counter > 0) {
balanceNew = balanceCurrent + (balanceCurrent *((interest_Rate /12)/100));
interestEarned = balanceCurrent *((interest_Rate /12)/100);
balanceCurrent = balanceNew + monthly_Deposit;
month = month + 1;
System.out.printf("%-11s %s %s %13s %s \n", month, dollarSign, df.format((balanceNew)), dollarSign, df.format(interestEarned));
counter = counter - 1;
}
System.out.print("Restart Calculator? Y/N);");
} while (scan.next() == "Y");
}
}
while (scan.next() == "Y"); // Is checking for reference equality
When doing object comparisons in Java, use equals()
while (scan.next().equals("Y"));
Or, as the previous answer pointed out you can compare characters with the == operator
Try this:
scan.nextLine().charAt(0) == 'Y'
When comparing Strings or anyother object for that matter you need to use the .equals(Object other) method. You can only use == with primatives ( boolean, int, double,...)
scan.nextLine().equals("Y");
//or
scan.next().equals("Y");
There is also an method to take the string to Uppercase that would allow the user to enter "y" or "Y"
scan.next().toUpperCase().equals("Y");
You should be using the Equals method for Strings:
while ("Y".equals(scan.next()));