I'm working on the hotel program and I have a problem with the my Queue class.
I need to create queue object in my program to add to queue and take from queue. Every time a name is added to a room it should use the queue object method to add the customer’s name to the queue. When the user selects to display the names of the first 3 customers my code should remove them from the queue one by one (first in first out) and display them as they are removed.
The queue should be based on an array. When the queue items reach the end of the array they should be added to the start or the array. If the queue becomes full the oldest queue item should be automatically removed and displayed.
The problem at the moment is when the end reaches 5 it should push the first input and take the last input and move it to the front of an array. Also please note the Queue must be based on string array. Please see the code i have so far, maybe some of you can help?
public class Queue {
static String qitems[] = new String[7];
static int front = 0, end = 0;
void addqueue(String name) {
System.out.println("Enter Queue Item :");
qitems[end] = name;
end++;
if(end==5){
takequeue(name);
}
}
void takequeue(String name) {
qitems[front]=name;
if (end > front) {
System.out.println("Item taken :" + qitems[front]);
front++;
} else {
System.out.println("Empty queue");
}
}
void displayqueue() {
System.out.println("Queue display: ");
for (int look = front; look < end; look++) {
System.out.println(" " + qitems[look]);
System.out.println("end"+end);
}
System.out.println("");
}
The addqueue() seems to have a logical flaw. Value of end gets increased by 1 before you check if(end==5). When the value of end becomes 6, the if statement is ignored, the takequeue() method is not invoked and you face the problem. To solve this, either add the if statement before end++ as
void addqueue(String name){
System.out.println("Enter Queue Item :");
qitems[end] = name;
if(end==5){
takequeue(name);
}
end++;
}
Or check for end>=5 rather than end==5 as:
void addqueue(String name){
System.out.println("Enter Queue Item :");
qitems[end] = name;
end++;
if(end>=5){
takequeue(name);
}
}
P.S. Please be more precise and clearer while asking a question from next time by using proper punctuation in your question description. Also see the How to ask questions section in the FAQ.
Alright so, i got my programm "finished" up to the point where i cant solve this simple problem.
i got this:
package hotel;
import java.util.Scanner;
/**
*
* #author Defalt
*/
public class Hotel {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Prices prices = new Prices();
Scanner user_in = new Scanner(System.in);
String method;
boolean taken = false;
boolean taken2 = false;
boolean taken3 = false;
boolean again = true;
//***********Introduction to the hotel*************
System.out.println("Welcome to Hotel Vermond's Heaven!");
System.out.println("We are happy to see that you would like to stay with us.");
//***********Creating of a Loop*************
do {
System.out.println("Please, type which room you would like to book: ");
System.out.println("Single Bed, Double Bed, President Suit");
method = user_in.nextLine();
//***********Choices of Rooms and Question to book another one*************
if ("Single Bed".equals(method)) {
System.out.println(prices.describe1());
if ("y".equals(user_in.nextLine())){
if(taken=true){
System.out.println("We are sorry, this room is already booked. Please choose another one");
}else again=true;
} else again=true;
} else if ("Double Bed".equals(method)){
System.out.println(prices.describe2());
if ("y".equals(user_in.nextLine())){
taken2 = true;
again=true;
} else again=true;
} else if ("President Suit".equals(method)){
System.out.println(prices.describe3());
if ("y".equals(user_in.nextLine())){
taken3 = true;
again=true;
} else again=true;
} else {
System.out.println("Please choose one of the rooms above.");
}
System.out.println("Would you like to book another Room(y/n)\n");
//***********Outbreak if User declines another booking*************
//***********Otherwise redo the whole process*************
if ("y".equals(user_in.nextLine())){
again=true;
} else{
break;
}
}while(again);
System.out.println("Thank you and goodbye!");
}
}
and my other class is this:
package hotel;
import java.util.Scanner;
/**
*
* #author Defalt
*/
public class Prices {
Scanner user_in = new Scanner(System.in);
int price1 = 300;
int price2 = 800;
int price3 = 2500;
//***********Information of the Room including Validation Question*************
public String describe1() {
return
"You Choose the Single Bed.\n\tThis room Contains 1 Bed, 1 Fridge a Bathroom but no View on the Ocean.\n\tThis room will cost CHF " + price1 + ".-.\n\tWould you like to book this room?(y/n)";
}
public String describe2() {
return
"You Choose the Double Bed.\n\tThis room Contains 1 Queen-size Bed, 1 Fridge a bathroom, an Icemaker but no View on the Ocean.\n\tThis room will cost CHF " + price2 + ".-.\n\tWould you like to book this room?(y/n)";
}
public String describe3() {
return
"You Choose the President Suit.\n\tThis room Contains 1 King-size Bed, 1 Fridge, XXL Bathroom, Private Entertainment-System, 65inch Flatscreen and a Balcony with View on the Ocean.\n\tThis room will cost CHF " + price3 + ".-.\n\tWould you like to book this room?(y/n)";
}
}
As you can see i tried to make the Single Bed a reserved room after it has been taken. Yet the System.out.println("We are sorry, this room is already booked. Please choose another one"); is shown even on the first booking.
why is that eventhough the initial value of my taken boolean is false?
what other option are there that i could take to make my idea work?
PS!: I think i got it working the first time BUT it kept the taken value on true no matter how often i close the program and restart it. (just a side note)
You need to change
if(taken=true){
System.out.println("We are sorry, this room is already booked. Please choose another one");
to
if(taken==true){
System.out.println("We are sorry, this room is already booked. Please choose another one");
Note the double equals in the if condition. This will check the value of taken instead of just always setting it to true, which is what is currently happening.
Alternatively, since taken is already a boolean value, you can simplify it to this:
if(taken){
System.out.println("We are sorry, this room is already booked. Please choose another one");
It would probably help you to catch these problems if you fixed your formatting and indentation. I tend to avoid omitting the curly braces at any time. This is generally java standard formatting:
if(condition) {
if(condition) {
// do the thing
}
else {
// do the other thing
}
}
else if(condition) {
// do another thing
}
else {
// do the third thing
}
Notice how ifs/else ifs/elses at the same nesting level are also kept at the same indentation level. This helps a lot with keeping them straight.
Edit:
Another thing I would like to point out is that you have the again boolean but you aren't using it. Instead of breaking out of the loop if the user is finished, use the again boolean you have like you should be and set it false. That will cause the loop condition to fail and exit the loop nicely. Using break is ugly.
Question is: How do i add code to ensure that a table number (tableNumberJTextField) and waiter name (waiterNameJTextField) have been entered? If one or all fields are empty Use a JOptionPane to inform user that both fields must contain Information
At the moment i have:
private void calculateBillJButtonActionPerformed(
ActionEvent event )
{
if(event.getSource() == tableNumberJTextField)
{
}
else
{
JOptionPane.showInputDialog("Information missing");
}
} // end method calculateBillJButtonActionPerformed
Would i need another IF...Else and a JOptionPane in there for WaiterName as well as tableNumberJTextField seen in the code above OR am i completely doing this wrong????
FULL QUESTION THAT I HAVE TO DO IS:
calculateBillJButtonActionPerformed method (which immediately follows dessertJComboBoxItemStateChanged) and add code to ensure that a table number (tableNumberJTextField) and waiter name (waiterNameJTextField) have been entered. If one of these fields is empty, display a JOptionPane informing the user that both fields must contain information. Otherwise, call the calculateSubtotal method, which you implement in the next step, to calculate the subtotal of the bill. The calculateSubtotal method takes no arguments and returns a double containing the subtotal, which you should display in subtotalJTextField. Calculate and display the tax and the total of the bill in JTextFields taxJTextField and totalJTextField, respectively. The tax rate is specified in a constant TAX_RATE.
Presumably, the actionPerformed you're showing is for a button. If so, just check for text in the fields:
String tableNumber = tableNumberJTextField.getText().trim();
String waiterName = waiterNameJTextField.getText().trim();
if (tableNumber.length() == 0 || waiterName.length() == 0)
{
// show an error
}
else
{
// do a calculation
}
The Prompt:
A program that accepts a candy name (for example, “chocolate-covered blueberries”), price per pound, and number of pounds sold in the average month, and displays the item’s data only if it is a best-selling item. Best-selling items are those that sell more than 2000 pounds per month.
b. A program that accepts candy data continuously until a sentinel value is entered and displays a list of high- priced, best-selling items. Best-selling items are defined in Exercise 2a. High-priced items are those that sell for $10 per pound or more.
Here is an example of a good design in operation:
High-priced, Best-selling Candy
Fudge $12.50 4500 lbs
Vanilla Creme $13.75 2200 lbs.
Fudge, 12.50, 4500 Jawbreakers, 6.50, 5500 Chocolate, 14.00, 790 Butterscotch, 9.50, 4500 Vanilla Creme, 13.75, 2200
Item that sold most pounds: Jawbreakers
but the problem I am having is that my teacher is not letting me use for loops, or arrays. And I do not want to define multiple instances of the same variable because it is finite to a certain amount.... What would be the most efficient way of doing this?
start
// Declarations
num QUIT = "Y";
final String HEADING = "High Priced, Best Selling Candy" + "\n" + "\n";
final String HSPS = candyName + " " + candyPrice + " " + candySold + " ";
final String MOSTSOLD = "Item that sold the most pounds is "
while <> QUIT;
enterCandy();
printHighPriceBestSelling();
printSoldMostPounds();
endwhile;
stop
entercandy()
String candyName = "poop";
double candyPrice = 0.0;
double candyWeight = 0.0;
int candySold = 0;
output "Please enter name of candy.";
input candyName;
output "Please enter candy price.";
input candyPrice;
output "Please enter pounds sold.";
input candySold;
printHighPriceBestSelling()
if(candySold > 2000 && candyPrice > 10)
{
output HEADING;
output HSPS;
}
else
{
output "There were/are no best selling, high priced candy!"
}
printSoldMostPounds();
//There is no basis for comparison.
There are only two ways of doing this. Create lots of different, artbitrary, and predefined variables to be filled by the loop until they are overwritten. Lets say 10. Or create an array. I am sure there is an overly complex way of doing it with nested if/switch/while loops, but why teach us/force us to use the ugly inefficient way?
output "MOSTSOLD ";
I'm assuming that, besides arrays, you're teacher isn't allowing you to use any standard Collection objects.
You could always just build your own LinkedList of entered candy orders--it's ugly, but it would work. A single "link" in the chain would look like this
public class CandyOrderLink {
private String candyName;
private Double candyPrice;
private Double orderAmount;
private CandyOrderLink nextOrderLink;
public CandyOrderLink(String candyName, Double candyPrice, Double orderAmount) {
this.candyName = candyName;
this.candyPrice = candyPrice;
this.orderAmount = orderAmount;
}
public CandyOrderLink getNextLink() {
return nextOrder;
}
public void setNextLink(CandyOrderLink nextOrderLink) {
this.nextOrderLink= nextOrderLink;
}
public String getCandyName() {
return candyName;
}
public Double getCandyPrice() {
return candyPrice;
}
public Double getOrderAmount() {
return orderAmount;
}
}
Not sure if I'm quite grasping the point of the assignment, but using a list data-structure to keep track of all orders will work. Just build a link for each entry (candyName, price, amount) and set that link as the next link of the previous one. At the end of input, iterate through the list by repeatedly calling getNextLink() on each link and printing information (if appropriate). Here is Wikipedia's article on linked lists: http://en.wikipedia.org/wiki/Linked_list
From the problem's description, I see no need to store the data entered so that it can be sorted. Both a and b state simple conditions for displaying a candy: greater than 2,000 pounds and at least $10/lb. You can print each entry immediately after it is entered.
However, your example output implies that you must pick the single best-selling candy which contradicts the description. Which is correct?
For my CS course I have to program a hotel checkin/checkout system. The program must be able to check people in and out. The programm assigns the first available room to a guest upon checkin. If no room is free, it will say so as well. The Hotel has four rooms.
In the assignment it says there need to be 4 classes: Assignment5, Hotel, Room, & Guest.
Assignment5 class is for the interaction with the user.
Hotel class has four rooms and all methods for operating the rooms.
Room class has 1 guest. If the rooms is empty a guest can check in. If the guest is leaving the room needs to be emptied.
Guest class: the guest has a firstname and a last name.
In the menu there need to be 4 options:
1 show status of rooms available and occupation.
2 check in option
3 check out option
4 end program option.
OK, so I know I should make my assignment for myself. However, I don't know what it is, but starting with assignments I have great problems cutting the thing up in smaller pieces. Also this assignment is to learn working with different classes and I don't really understand which sequence of steps i should take in this case.
Can someone help me getting started by giving some tips? Have been staring at my screen for hours now and just thought I could use some little insights to get me started. Any help is greatly apprecieted!
OK thnks for the help so far.
**First of all, MANY thanks for all your help, you guys are great! Have been at it for 7 hours straight now and still stuck. My problem now is that it doesn't compile. It says:
Java:28: checkIn(Gast) in Hotel cannot be applied to (java.lang.String)
hotel.checkIn("Guido");
^
1 error
And maybe, can someone look if this way i put it now is a little bit on the right path? I do thank JavaGeek for his program, but i want to learn it by doing myself.
up until now I have the following:
import java.util.Scanner;
public class bopgave5 {
public static void main(String[] args) {
boolean opnieuw = false;
do {
int invoer = menu();
if (invoer == 2){
Hotel hotel = new Hotel();
hotel.checkIn("Guido");
opnieuw = true;
}
else if (invoer == 4)
opnieuw = false;
else
opnieuw = true;
}
while (opnieuw == true);
}
public static int menu (){
Scanner sc = new Scanner(System.in);
System.out.println("MENU: [1] Statusoverzicht");
System.out.println(" [2] Check-in");
System.out.println(" [3] Check-out");
System.out.println(" [4] Einde");
System.out.print("Uw invoer: ");
int invoer = sc.nextInt();
return invoer;
}
}
class Hotel {
Kamer kamer1, kamer2, kamer3, kamer4;
Hotel (){
kamer1 = new Kamer();
kamer2 = new Kamer();
kamer3 = new Kamer();
kamer4 = new Kamer();
}
void checkIn(Gast nieuweGast) {
if (kamer1.gast == null) {
kamer1.gast = nieuweGast;
System.out.println("Gast " + nieuweGast.naam + " krijgt kamer 1");
return;
}
else if (kamer2.gast == null) {
kamer2.gast = nieuweGast;
System.out.println("Gast " + nieuweGast.naam + " krijgt kamer 2");
return;
}
else if (kamer3.gast == null) {
kamer3.gast = nieuweGast;
System.out.println("Gast " + nieuweGast.naam + " krijgt kamer 3");
return;
}
else if (kamer4.gast == null) {
kamer4.gast = nieuweGast;
System.out.println("Gast " + nieuweGast.naam + " krijgt kamer 5");
return;
}
else {
System.out.println("hotel is vol");
return;
}
}
}
class Kamer {
Gast gast;
Kamer() {
gast = null;
}
}
class Gast {
String naam;
Gast(String nieuweNaam) {
naam = nieuweNaam;
}
}
So you have 4 classes.
In the assignment it says there need
to be 4 classes: Assignment5, Hotel,
Room, & Guest.
With the division of responsibility as such:
Assignment5 class is for the
interaction with the user.
Hotel class has four rooms and all
methods for operating the rooms. (extra emphasis: "rooms" is plural)
Room class has 1 guest. If the rooms
is empty a guest can check in. If the
guest is leaving the room needs to be
emptied. (or in other word, operating a single room)
Guest class: the guest has a firstname
and a last name.
First, you'd probably want to identify the "state" that each object would have. IOW, you need to determine the attributes/instance fields that each object have. Let's start with an example: Guest class: the guest has a firstname and a last name.. Do the same for all the other classes.
Next, you want to identify the methods that will be needed. Let's start with another example: Room class has 1 guest. If the rooms is empty a guest can check in. If the guest is leaving the room needs to be emptied.. On top of that, you'll need some constructors for each class.
Next, for each method, you want to find out the arguments that the method needs, and their return values, if they need to return a value. For example, for a check in method, you'll need the Room and a Guest; and you'll need to check whether the room is empty before you can check in.
UPDATE:
My problem now is: how can i make it work that there are 4 rooms and that after checking in 1 person, checking in a second person will put it in a different room?
Your teacher has a good advice, break it into pieces.
Basically, you have the problem: "Checking in the second person should put him in a different room".
So, how do we break this down? First, we need to find an empty room, so we need a method for that (say findEmptyRoom()), and after we find a room that's available, we need to check in the guest into that room, so we need another method (say checkIn()). So, we find an empty room, then we checked the guest into that room, then we're done.
Next step, we break findEmptyRoom(). Our hotel has 4 rooms (let's say we store room1, room2, room3, and room4 as member variables, alternatively, you can use an array if you already learn about it in class). To find which one of the four rooms are empty, we need to ask a room if it is empty; so we need another method for that (say isEmpty()). To find an empty room, ask room 1, if room1 is empty return room1, otherwise ask room 2, if room2 is empty return room2, otherwise ask room 3, if room3 is empty, return room3, otherwise ask room 4, if room4 is empty, return room4. Otherwise, all rooms are occupied. [note: you will need to figure out what to do if all rooms are occupied]. An array will make this process much easier, you just need to loop through the array, and ask if it's empty and return the room if it's empty, otherwise continue checking next room.
Next, we break checkIn(). So, what do checkIn() need to know to fulfill the checking in process? It needs to know about two information: the room and the guest. Since checkIn() is an instance method of a room class, room is implied, so we only need one parameter, i.e. guest. So void checkIn(Guest guest) should set the guest member variable of the room.
Next, we break isEmpty(). How do we know if a room is empty? If a room has a guest inside it, then it's occupied, otherwise it's empty. So, isEmpty() checks if the guest member variable refers to a valid guest, returns true if it is valid guest, otherwise returns false. In Java, null is often used to mark that something is not a valid object, so you can check whether the guest member variable is null (obviously, you'll need to set the guest member variable to null when a guest checked out).
Do the same thing for the other processes. Break the problem down into smaller pieces until you're confident that you can work with a piece.
UPDATE2:
The error message you've got:
Java:28: checkIn(Gast) in Hotel cannot be applied to (java.lang.String)
hotel.checkIn("Guido");
is because you're passing a String ("Guido") to a function that takes a Gast argument (void checkIn(Gast nieuweGast) {...}). You should instead, pass a Gast object:
// declare a variable called g, with type Gast
Gast g;
// create a new Gast object, passing "Guido" as parameter
// to Gast's constructor, and assign the new object to g
g = new Gast("Guido");
// call hotel.checkIn(Gast) function with g as the argument,
// i.e. the Gast object we just created in the previous line
hotel.checkIn(g);
or more simply:
hotel.checkIn(new Gast("Guido"));
Short of solving this thing for you, here is what I would suggest you do.
Think of each operation that needs to be performed, and then diagram the logic that needs to take place to accomplish that operation. Then, with a clear list of logical operations that need to take place to accomplish that task, think carefully about what components you can break that operation up into and where each of those sub-tasks should go. This will give you a good idea of what the class diagram should look like. Once you've diagrammed the logic, classes/methods, and implemented one part, move on to the next part. At this point, you'll probably find that something wasn't structured in a way that allows it to be reused for the next task, so refactor it (modify the structure of the code) to make it more reusable.
For example, tackle the check-in operation. What do you need to do first? Well, first you need determine if there are any rooms available. How do you do that? You need to ask all of the rooms (by your design, if I remember correctly) if they are available. So, we can now identify that we need a method on the rooms to tell us that they are available. Maybe tackle that first. Then the checking for a free room part. That probably goes on the hotel class. You'll need to iterate over the rooms and ask them if they are free. After this, you need to decide what to do if there is a free room(s), or if there aren't any. I guess you display an error message if there aren't? If there are free rooms, you need form the check-in operation. Write that. Rinse and repeat. Before long, you'll have a functioning program.
The important thing to remember here is that there are MANY different ways to accomplish this in an object-oriented manner. When you are just learning OO design and the basics of programming, it is important to not get too hung up on the perfect design and to dive in. Then when you are in the middle of implementing it, I'm sure you'll say 'hey, if I do it this way it will come up much better'. I like to think of this as an iterative learning process.
Start with the objects, the domain
Try giving the classes useful members. What is a 'hotel' for this problem? When they have useful members, what are useful operation on them, the methods?
Fields: A room should have a room number. A room should know what guest is staying in that room. A guest should have a name. A hotel should have a collection of rooms, a name, an address? Maybe the address is useless here.
Methods: A room should have a method to see if it's empty and what guest is staying there if it is not empty. A hotel should have a method that tells you how many rooms are available, or give you the actual rooms. All the guests that stay in the hotel? Etc, etc, etc.
You'll notice you will have to keep refining, changing, fixing your model to be able to meet the requirements. For example 'checking in' might need a new method in room you did not yet have.
//Guest.java
package hotelcheckinsystem;
class Guest {
private String name;
public String getName() {
return name;
}
public Guest(String name) {
super();
this.name = name;
}
public void setName(String name) {
this.name = name;
}
}
//Room.java
package hotelcheckinsystem;
class Room {
private Guest guest;
public Guest getGuest() {
return guest;
}
public void setGuest(Guest guest) {
this.guest = guest;
}
public void removeGuest() {
guest.setName("");
}
public boolean isEmpty() {
if (this.getGuest().getName().equalsIgnoreCase("")) {
return true;
}
return false;
}
}
//Hotel.java
package hotelcheckinsystem;
public class Hotel {
private Room[] rooms = new Room[4];
public Hotel() {
for (int i = 0; i < 4; ++i) {
rooms[i] = new Room();
Guest guest = new Guest("");
rooms[i].setGuest(guest);
}
}
public void assignRoomToGuest(String name) {
int i;
for (i = 0; i < 4; ++i) {
if (rooms[i].isEmpty()) {
Guest guest = new Guest(name);
rooms[i].setGuest(guest);
System.out.println("Room number " + i + " assigned to " + name);
return;
}
}
if (i == 4) {
System.out.println("No empty Rooms to assign to " + name);
}
}
public void emptyRoom(int roomNo) {
if (roomNo > 3) {
System.out.println("please enter number between 0 to 3");
return;
}
rooms[roomNo].removeGuest();
System.out.println("Room number " + roomNo + " is empty now!.");
}
}
//Main.java
import java.util.Scanner;
import hotelcheckinsystem.*;
public class Main {
public static void main(String[] args) {
Hotel hotel = new Hotel();
while (true) {
System.out.println("Enter the Option: ");
System.out.println("1. Check in. \n2. Check out. \n3. Exit");
Scanner sc = new Scanner(System.in);
int option = sc.nextInt();
switch (option) {
case 1:
System.out.println("Enter the guests name");
hotel.assignRoomToGuest(sc.next());
break;
case 2:
System.out.println("Enter the Room number");
hotel.emptyRoom(sc.nextInt());
break;
case 3:
System.exit(0);
}
}
}
}
Sample Run:-
Enter the Option:
Check in.
Check out.
Exit
1
Enter the guests name
empty
Room number 0 assigned to empty
Enter the Option:
Check in.
Check out.
Exit
1
Enter the guests name
A
Room number 1 assigned to A
Enter the Option:
Check in.
Check out.
Exit
1
Enter the guests name
B
Room number 2 assigned to B
Enter the Option:
Check in.
Check out.
Exit
1
Enter the guests name
C
Room number 3 assigned to C
Enter the Option:
Check in.
Check out.
Exit
1
Enter the guests name
D
No empty Rooms to assign to D
Enter the Option:
Check in.
Check out.
Exit
2
Enter the Room number
1
Room number 1 is empty now!.
Enter the Option:
Check in.
Check out.
Exit
1
Enter the guests name
D
Room number 1 assigned to D
Enter the Option:
Check in.
Check out.
Exit
3
I can see you already made some code but for your next similar assignment I would code the classes in the following way.
Guest
Room
Hotel
Assignment5 <-- This is the most complicated one and is something you can do at last.
Why?
Guest is really easy to code. When that is done go on to Room. Room is gonna need the class Guest. After you finished Room go code Hotel. Hotel is gonna use Room.
From what I can understand from your (dutch)code you store a guest as a String. This is not the purpose of the assignment. It is supposed to store a Guest object.
I hope this will help you.
I'm joining this a little late, but the reason for the error is you are attempting to check in a String called Guido instead of a Guest (Gast) with the name field of Guido. You would need some lines like the following:
Gast guido = new Gast("Guido");
hotel.checkIn(guido); // this was previously hotel.checkIn("Guido")