I am supposed to make this code output Day total and then the number of hours worked for that day. The code is currently displaying the day and the total. But it is displaying too many times for the program to even register. For instance, it asks to input a day, and I'll put in Monday. Then the number of hours worked, and I'll put 6. It will then output Monday 6.0 thousands of times. The expected output should be Day Total 6. What am I missing or is added to cause this?
// SuperMarket.java - This program creates a report that lists weekly hours worked
// by employees of a supermarket. The report lists total hours for
// each day of one week.
// Input: Interactive
// Output: Report.
import java.util.Scanner;
public class SuperMarket
{
public static void main(String args[])
{
// Declare variables.
final String HEAD1 = "WEEKLY HOURS WORKED";
final String DAY_FOOTER = " Day Total "; // Leading spaces are intentional.
final String SENTINEL = "done"; // Named constant for sentinel value.
double hoursWorked = 0; // Current record hours.
String hoursWorkedString = ""; // String version of hours
String dayOfWeek; // Current record day of week.
double hoursTotal = 0; // Hours total for a day.
String prevDay = ""; // Previous day of week.
boolean done = false; // loop control
Scanner input = new Scanner(System.in);
// Print two blank lines.
System.out.println();
System.out.println();
// Print heading.
System.out.println(HEAD1);
// Print two blank lines.
System.out.println();
System.out.println();
// Read first record
System.out.println("Enter day of week or done to quit: ");
dayOfWeek = input.nextLine();
if(dayOfWeek.compareTo(SENTINEL) == 0)
done = true;
else
{
System.out.print("Enter hours worked: ");
hoursWorkedString = input.nextLine();
hoursWorked = Integer.parseInt(hoursWorkedString);
prevDay = dayOfWeek;
}
while(done == false)
{
System.out.println(dayOfWeek + " " + hoursWorked);
hoursTotal = 0;
prevDay = hoursWorkedString;
}
System.out.println(dayOfWeek + " " + hoursWorked + hoursTotal);
hoursTotal++;
if(dayOfWeek.compareTo(SENTINEL) == 0)
{
hoursWorked = dayOfWeek.compareTo(SENTINEL);
prevDay = dayOfWeek;
done = true;
}
else
done = false;
// Include work done in the dayChange() method
if(dayOfWeek.compareTo(SENTINEL) == 0)
System.out.println(DAY_FOOTER + hoursTotal);
System.exit(0);
} // End of main() method.
} // End of SuperMarket class.
while(done == false)
{
System.out.println(dayOfWeek + " " + hoursWorked);
hoursTotal = 0;
prevDay = hoursWorkedString;
}
In this code block, you aren't changing done variable, so it is an infinite loop.
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
This program is supposed to add the hours from the input until the input ='s "done" but even after the input ='s "done" and the boolean is set to true in the while loop, it doesn't end the loop, and I can't figure out why. If someone inputs for example,
Friday
4
done
the code should output the day total and 4 as a result but it doesn't break the loop, and multiple inputs don't add the number of hours.
import java.util.Scanner;
public class SuperMarket
{
public static void main(String args[]) throws Exception
{
// Declare variables.
final String HEAD1 = "WEEKLY HOURS WORKED";
final String DAY_FOOTER = " Day Total "; // Leading spaces are intentional.
final String SENTINEL = "done"; // Named constant for sentinel value.
double hoursWorked = 0; // Current record hours.
String hoursWorkedString = ""; // String version of hours
String hoursTotalString = "";
String dayOfWeek; // Current record day of week.
double hoursTotal = 0; // Hours total for a day.
String prevDay = ""; // Previous day of week.
boolean done = false; // loop control
Scanner input = new Scanner(System.in);
// Print two blank lines.
System.out.println();
System.out.println();
// Print heading.
System.out.println(HEAD1);
// Print two blank lines.
System.out.println();
System.out.println();
// Read first record
System.out.println("Enter day of week or done to quit: ");
dayOfWeek = input.nextLine();
if(dayOfWeek.compareTo(SENTINEL) == 0)
done = true;
else
{
System.out.print("Enter hours worked: ");
hoursWorkedString = input.nextLine();
hoursWorked = Integer.parseInt(hoursWorkedString);
hoursTotal= hoursTotal+hoursWorked;
prevDay = dayOfWeek;
System.out.println("\t" + DAY_FOOTER + String.valueOf(hoursTotal));
}
while(done == false){
System.out.println("Enter day of week or done to quit: ");
dayOfWeek = input.nextLine();
if( prevDay != dayOfWeek){
hoursTotal =0;
}
System.out.print("Enter hours worked: ");
hoursWorkedString = input.nextLine();
prevDay = dayOfWeek;
hoursTotal= hoursTotal+hoursWorked;
System.out.println("\t" + DAY_FOOTER + String.valueOf(hoursTotal));
if(dayOfWeek == "done"){
done = true;
break;
}
}
System.out.println(DAY_FOOTER + "(" + prevDay + ") " + hoursTotal);
System.exit(0);
} // End of main() method.
} // End of SuperMarket class.
The problem is your String comparetion, you shouldn't really compare two Strings with ==, but with .equals() method.
Just change this line:
if(dayOfWeek == "done") ...
to:
if(dayOfWeek.equals("done")) ...
I am very new to coding and I have a simple question. I want to input day, month and year inside a for loop and after inputting it I want to display all the inputted values on the same time. how to do it.kindly help me.
i have attached the code below.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i=0;i<n;i++) {
int day = in.nextInt();
String month = in.next();
int year = in.nextInt();
}}
//need to display the entire content from the for loop
//suppose if the n value is 3
//i will be giving 3 inputs
//10 jan 1998
//11 nov 2000
//12 dec 1995
//i want to print all at the same time
Kindly help me with it.
If I understood your question correctly and you just want to print your inputs, just add the following to the loop:
System.out.println(String.format("%d %s %d", day, month, year));
or otherwise, but not as pretty (at least in my opinion):
System.out.println(day + " " + day + " " + month + " " + year);
EDIT
As indicated, you want to print them all at the same time. To do so, you can just save them all in a list or an array for example like the following:
Before the loop:
String[] dates = new String[n];
In the loop:
dates[i] = String.format("%d %s %d", day, month, year);
And then go ahead and insert another loop to print the content of the array:
for(String date: dates){
System.out.println(dates[i]);
}
From what I have gathered, you are looking to set a number on how many dates you'd like the user to enter, take in that number of dates and then print out the dates after the user input.
Here is some basic code that will do that for you
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int numOfInputs = 3; //How many separate dates you would like to enter
int day[] = new int[numOfInputs]; //declaring an integer array day and setting the array size to the value of numOfInputs
String month[] = new String[numOfInputs]; //declaring a string array month and setting the array size to the value of numOfInputs
int year[] = new int[numOfInputs]; //declaring an integer array year and setting the array size to the value of numOfInputs
//get inputs
for(int i=0;i<numOfInputs;i++) {
System.out.println("Please enter a day");
day[i] = sc.nextInt();
System.out.println("Please enter a month");
month[i] = sc.next();
System.out.println("Please enter a year");
year[i] = sc.nextInt();
}
//print content
for(int i=0;i<numOfInputs;i++) {
System.out.println(day[i] + " " + month[i] + " " + year[i]);
}
//close scanner
sc.close();
}
Let me know if this doesn't answer your question or if you need any clarification.
My program consists of several options of what to do with user input data about shows (name, day, time). One of the options is to display the data and the total number of shows per day (ex: if there are 2 shows on Tuesday, it will display "There are 2 shows on Tuesday"). So far the output for displaying all the data is working but when it comes to displaying the number of shows on a specific day, it isn't working properly. I've read several other java programs that seem to have a switch statement on each day but that hasn't worked either. If there are any suggestions on what I should change about my code, I would truly appreciate it! Thank you
I have edited my code from the previous one but it still hasn't worked
Note: the int dayCount is placed in the enter data method; after the day[i] = br.readLine();
Here is my class:
import java.io.*;
public class Javavision {
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static String name[] = new String[1000];
static String day[] = new String[1000];
static String time[] = new String[1000];
static int dayCount = 0;
static int x, i, j, smallest;
static String temp;
Here is my code:
public static void showShows() {
//output all shows
for (i = 0; i < x; i++) {
System.out.println("Name : " + name[i]);
System.out.println("Day : " + day[i]);
System.out.println("Time(2:30 am = 0230) : " + time[i] + "\r");
} **The problem is here**
for (i = 0; i < x; i++) {
if(i ==0) {
System.out.println("There is " + dayCount + " shows on " + day[i]);
}
}
}
Here is the output:
Name : The Flash
Day : Sunday
Time(2:30 am = 0230) : 0125
Name : Suits
Day : Sunday
Time(2:30 am = 0230) : 0450
Name : Java Program
Day : Tuesday
Time(2:30 am = 0230) : 0330
There is 3 shows on Sunday
This is where I increment dayCount:
//Method addShow
public static void addShow() throws IOException {
//initialize counter
x = 0;
do {
//Update Array
System.out.println("Enter Name of Show: ");
name[x] = in.readLine();
System.out.println("Enter Day of Show: ");
day[x] = in.readLine();
dayCount++;
System.out.println("Enter Time of Show (ex: 2:30am = 0230) : ");
time[x] = in.readLine();
//Increase counter
x++;
//Ask if the user wants to stop
System.out.println("\nTo continue press Enter ");
System.out.println("To Quit, type in 'quit': ");
}
while((in.readLine().compareTo("quit"))!=0);
//Method addShow()
}
In your loop that prints the total shows you have:
for (i = 0; i < x; i++) {
if(i ==0) {
System.out.println("There is " + dayCount + " shows on " + day[i]);
}
}
The if(i == 0) makes it so that the println only executes on the first iteration of the loop. Take out the if statement and have:
for (i = 0; i < x; i++) {
System.out.println("There is " + dayCount + " shows on " + day[i]);
}
And this should print out the rest of the days
Also you only have one dayCount variable that you use for all the days. So no matter what day a show is on, you increment dayCount. (If you have three shows on different days you still increment dayCount everytime so it shows that you have three shows on each day when you print it out) If you want to have a separate dayCount variable for every day, I recommend using a Hashmap.
(Using the day as the key and the dayCount as the value)
Also you could look into enums to use for the days of the week.
I am new to java and I am trying to figure out how to get the user input of time validated. If the user inputs a number lower then 800 or a number higher then 1900 the they should get the proper error message. I also want the user to get an error message if they input a time like 860 etc... I've been wrapped around this part for too long and I definitely need help.
import java.util.Scanner;
public class FugonIsaac06 {
public static void main(String[] args) {
boolean keepAsking = true;
Scanner reader = new Scanner(System.in);
String userInput = "";
int input_Start = 0;
int input_End = 0;
while (keepAsking) {
System.out.print("Please enter your name: ");
userInput = reader.nextLine();
if (userInput.length() >= 3) {
keepAsking = false;
} else {
System.out.println("Name must be at least 3 characters long.");
}
}
keepAsking = true;
//You will need to somehow separate the hours and minutes from the input.
//Use integer division and modulus to separate hours and minutes.
//Hours = Input / 100
//Minutes = Input % 100
//To convert the minutes to parts of an hour divide the minutes by 60.0.
//Parts of an hour = Minutes / 60.0
int hours_Start = input_Start / 100;
int minutes_Start = input_Start % 100;
while (keepAsking) {
System.out.print("Enter start time: ");
input_Start = reader.nextInt();
if ((input_Start > hours_Start) &&
(input_Start < minutes_Start)) {
keepAsking = true;
System.out.println("Start time should be between 800 and 1900");
} else {
System.out.println("Time is malformed, minutes should be between 0 and 59");
}
}
}
}
I would refactor your code to something like this:
Scanner reader = new Scanner(System.in);
String username = "";
do {
username = reader.nextLine();
} while(username.length() < 3);
int timeStart;
String timestamp = "";
// enter a timestamp in the form of hoursminutes
// hours = 0 (or 00) to 23
// minutes = 0 (or 00) to 59
do {
timestamp = reader.nextLine();
} while(!timestamp.matches("(?:2[0-3]|[0-1][0-9])[0-5][0-9]"));
// parse out the hours and minutes components
int hours = Integer.parseInt(timeStart) / 100;
int minutes = Integer.parseInt(timeStart) % 100;
Using do loops works well for your use case, because you want to eagerly accept an initial user input, regardless of any previous state, yet you want to have the ability to loop back again should validation fail. The while conditions validate the input, checking that a username have 3 or more characters, and that the time start is within the range you specified.
I have edited your code try it
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
boolean keepAsking = true;
Scanner reader = new Scanner(System.in);
String userInput = "";
int input_hours =0;
int input_End = 0;
String time;
while (keepAsking) {
System.out.print("Please enter your name: ");
userInput = reader.nextLine();
if (userInput.length() >= 3) {
break;
// keepAsking = false;
} else {
System.out.println("Name must be at least 3 characters long.");
}
}
keepAsking = true;
//You will need to somehow separate the hours and minutes from the input.
//Use integer division and modulus to separate hours and minutes.
//Hours = Input / 100
//Minutes = Input % 100
//To convert the minutes to parts of an hour divide the minutes by 60.0.
//Parts of an hour = Minutes / 60.0
int hours_Start = 0;
int minutes_Start = 0;
while (keepAsking) {
System.out.print("Enter start time HH:MM : ");
time = reader.next();
String []timeArr = time.split(":");
input_hours = Integer.parseInt(timeArr[0]);
minutes_Start = Integer.parseInt(timeArr[1]);
if (input_hours > 19 || input_hours < 8) {
keepAsking = true;
System.out.println("Start time should be between 800 and 1900");
} else if(minutes_Start<0 || minutes_Start>59){
System.out.println("Time is malformed, minutes should be between 0 and 59");
}else{
System.out.println("You have entered correct time");
break;
}
}
}
}
I'm having a little problem here.
We been told to program some simple things but I can't run the code perfectly with if statement.
With while statements, my code works perfectly but teacher insists not to use it.
While statement is a loop right?
He said "Do not use loops!".
import java.util.Scanner;
public class Flight
{
public static void main (String [] args)
{
// Naming a scanner //
Scanner scan = new Scanner(System.in);
// Prints text //
System.out.println("Enter flight day: ");
// Data insert //
int flyDay = scan.nextInt();
System.out.println("Enter flight hour: ");
int flyHour = scan.nextInt();
System.out.println("Enter flight minute: ");
int flyMinute = scan.nextInt();
//// Length ///
System.out.println("Enter flight's length in hours:");
int departureHour = scan.nextInt();
System.out.println("Enter flight's length in minutes:");
int departureMin = scan.nextInt();
// While minute is beyond 60 (including) //
departureMin += flyMinute;
while(departureMin >= 60) {
departureHour++;
departureMin-=60;
}
// While hour is beyond 24 (including) //
departureHour += flyHour;
while(departureHour >= 24)
{
flyDay++;
departureHour-=24;
}
// While day is beyond 8 (including) //
while(flyDay >=8)
flyDay-=7;
// Prints arrival time according to the data inserted above //
System.out.println("the supposed arrival time is: day- " + flyDay + ", hour- " + departureHour + ", minute- " + departureMin);
}
}
If I switch the while statements into if statements the code will not work properly.
Any help?
Your teacher is correct, it's not appropriate to use a loop here, even though it works.
Your teacher probably wants you to use the remainder (%) (frequently called "modulus") operator and the division (/) operator.