making an option >reserved< with boolean? - java

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.

Related

I have made a Java programme but has repetition problem

I have created that Java programme but it have repetition problem, I want that if one question has done either right or wrong it must not be ask again.
It should ask 10 question only. I have tried alot to change but every time I am getting error.
I have created that Java programme but it have repetition problem, I want that if one question has done either right or wrong it must not be ask again.
It should ask 10 question only. I have tried alot to change but every time I am getting error.
package examapp;
import java.util.Random;
import javax.swing.JOptionPane;
public class Examapp {
static int nQuestions = 0; static int nCorrect = 0;
public static void main(String[] args) {
int prevNum=0;
int sum=0;
do{
Random rand = new Random();
int randomNum = rand.nextInt((11 - 1) + 1) + 1;
if(randomNum==prevNum){
prevNum=randomNum;
}
else if(randomNum==1){
String question1;
question1 = "What was the name of Google in late 90s?\n";
question1+="A. Googol\n";
question1+="B. Gigablast\n";
question1+="C. Backrub\n";
question1+="D. Google\n";
question1+="Marks=9";
check(question1,"C");
sum=sum+1;
}
else if(randomNum==2){
String question2;
question2 = "\"Do no evil\" is a tagline of?\n";
question2+="A. Yahoo\n";
question2+="B. Google\n";
question2+="C. Bing\n";
question2+="D. Duck Duck Go\n";
question2+="Marks=9";
check(question2,"B");
sum=sum+1;
}
else if(randomNum==3){
String question3;
question3 = "Which of the following is fully Object Oriented Programming Language?\n";
question3+="A. SmallTalk\n";
question3+="B. Kotlin\n";
question3+="C. Java\n";
question3+="D. F#\n";
question3+="Marks=9";
check(question3,"A");
sum=sum+1;
}
else if(randomNum==4){
String question4;
question4 = "Which among the following is not a mobile Operating System?\n";
question4+="A. Bada\n";
question4+="B. Safari\n";
question4+="C. WebOS\n";
question4+="D. MeeGo\n";
question4+="Marks=9";
check(question4,"B");
sum=sum+1;
}
else if(randomNum==5){
String question5;
question5 = "Which of the following is a correct format of Email address?\n";
question5+="A. info.website.com\n";
question5+="B. info#website.com\n";
question5+="C. info#website#com\n";
question5+="D. info.website#com\n";
question5+="Marks=9";
check(question5,"B");
sum=sum+1;
}
else if(randomNum==6){
String question6;
question6 = "What is the shortcut key of printing a document for computer having windows?\n";
question6+="A. Ctrl + Shift + P\n";
question6+="B. Alt + P\n";
question6+="C. Ctrl + Alt + P\n";
question6+="D. Ctrl + P\n";
question6+="Marks=9";
check(question6,"D");
sum=sum+1;
}
else if(randomNum==7){
String question7;
question7 = "Computer software includes\n";
question7+="A. Packaged programs\n";
question7+="B. Operating system programs\n";
question7+="C. Applications programs\n";
question7+="D. All of these\n";
question7+="Marks=9";
check(question7,"D");
}
else if(randomNum==8){
String question8;
question8 = "A function inside another function is called a _______ function\n";
question8+="A. Nested\n";
question8+="B. Round\n";
question8+="C. Sum\n";
question8+="D. Grouped\n";
question8+="Marks=9";
check(question8,"A");
sum=sum+1;
}
else if(randomNum==9){
String question9;
question9 = "What does HTTP stands for?\n";
question9+="A. Hypertext Transfer Plotter\n";
question9+="B. Hypertext Transfer Plot\n";
question9+="C. Hypertext Transfer Protocol\n";
question9+="D. Head Tail Transfer Protocol\n";
question9+="Marks=9";
check(question9,"C");
sum=sum+1;
}
else if(randomNum==10){
String question10;
question10 = "The term 'Pentium' is realted to\n";
question10+="A. DVD\n";
question10+="B. Hard Disk\n";
question10+="C. Microprocessor\n";
question10+="D. Mouse\n";
question10+="Marks=9";
check(question10,"C");
sum=sum+1;
}
else{
prevNum=randomNum;
}
}while(sum<=9);
JOptionPane.showMessageDialog(null,nCorrect + " correct out of 10" + " questions");
JOptionPane.showMessageDialog(null,"Total Obtained Marks="+(nCorrect*9));
}
public static String ask(String question) {
while(true) {
String answer = JOptionPane.showInputDialog(question);
answer = answer.toUpperCase();
if(!(answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("D"))){
JOptionPane.showMessageDialog(null,"Invalid Answer");
continue;
}
return answer;
}
}
static void check(String question, String correctAnswer) {
nQuestions++;
String answer = ask(question);
if(answer.equals(correctAnswer)) {
nCorrect++;
}
else {
}
}
}
Thank you!
Your main is quite cluttered. By the time you get to the bottom, you have already forgotten what was on top, such as that it is a very large do-while block. If I were you, I would put the questions and answers in an array, list or even better in your own question object. Then you could use array shuffle to put them in different order for each run and omit all the if-else blocks. It is best to also pull your initialization from random out of the loop so that you don't create a new object with every iteration.
In order to answer your question, so that you do not use an already generated random number again, you must somehow remember the already generated ones. For example, use a list.
public static void main(String[] args) {
Random rand = new Random();
List<Integer> list = new ArrayList<>();
int count = 0;
int randomNum;
do{
randomNum = rand.nextInt(10)+1;
while(list.contains(randomNum)){
randomNum = rand.nextInt(10)+1;
}
list.add(randomNum);
count++;
// rest of your code goes here
}while( count < 10);
System.out.println(list);
}

How do I call a method recursively?

I'm trying to recursively call a method until I obtain the desired output. However, I want to call a method from another class and get information from that method in order to use it in my recursive method. For example, suppose I have a parent class called Cake that contains information about a cake such as its batter(i.e. amount the batter), an extended class with a specific type of cake containing a unique instance of the batter, and I have another class called Bakery where I want to actually make cakes that are being ordered. I have a method in Bakery called createCake, and I want to recursively call this method until enough batter is in the pan to create a cake. If the amount of batter is randomly generated in the extended class, how do I call the getBatter method from that class and capture the information about the batter amount in order to use it in my recursive method for creating the cakes? Can anyone help me out with this? I'm doing something similar to this, but I don't quite understand how I would go about actually getting the information in order to get the recursion to work. I have an example of the code below, so that you can have an idea of what I'm trying to do (I know it's not very accurate). Any help would be greatly appreciated.
import java.util.Random;
public abstract class Cake
{
static Random gen = new Random(System.currentTimeMillis());
public int type; //type of cake
public static int batter = gen.nextInt() * 3; //random amount of batter
public int getType()
{
return type;
}
public int getBatter()
{
return batter;
}
}
public class RedVelvet extends Cake
{
public int type;
public int batter = gen.nextInt(3)+6; //generates between 6-8 cups of batter inclusive
public int getType()
{
return 1;
}
public int getBatter()
{
return batter;
}
}
public class Chocolate extends Cake
{
public int type;
public int batter = gen.nextInt(3)+6; //generates between 6-8 cups of batter inclusive
public int getType()
{
return 2;
}
public int getBatter()
{
return batter;
}
}
public class Pound extends Cake
{
public int type;
public int batter = gen.nextInt(3)+6;
public int getType()
{
return 3;
}
public int getBatter()
{
return batter;
}
}
public class Bakery
{
import java.util.Scanner;
System.out.print("Enter desired size of cake to be baked (Must be at least 12):");
desiredSize=scan.nextInt();
public static void createCake(int desiredSize, int currentSize) //currentSize is the current amount of batter in the pan
{
if (currentSize == desiredSize)
return;
else if (currentSize < desiredSize)
{
//Recursively call createCake method so that batter continues to be added to the pan until there is enough to make the desired cake size. I want to get the batter information from one of the extended classes in order to add it to the cake.
}
}
Is this for school or a course of sorts because I personally wouldn't go this route but then again that's my opinion. It's like, what the heck do I know about baking and I can safely tell you....absolutely nothing. Some may even say that about my programming/coding skills but then again, I'm not a programmer and I am self taught in almost all programming environments including good old Assembly most of which I have now forgotten. :/
I should think that when it comes to baking cakes (or most things for that matter) some sort of accuracy must be established so as to avoid waste and we all know that waste costs money. I'm not overly convinced that generating random amounts of cake batter is accurate enough for what you're most likely are trying to accomplish but then again, you already know this. I noticed that in your different cake classes they all basically generate a random number from 6 to 8. If they all do the same thing then why have them?
I don't believe you need recursion at all but instead a simple method called from within a loop, for example:
while (currentSize < desiredSize) {
currentSize+= getBatter(cake, desiredSize);
}
Here is how I would do this and I apologize now if you find this is all totally meaningless:
import java.util.Random;
import java.util.Scanner;
public class Bakery {
public static void main(String[] args) {
getBaking(); // :)
}
private static void getBaking(){
Scanner scan = new Scanner(System.in);
String cakeType = "";
while (cakeType.equals("")) {
System.out.print("Enter desired cake to be baked (Pound, Chocolate, "
+ "RedVelvet) or\nenter 'exit' to quit: -> ");
cakeType = scan.nextLine();
if (cakeType.isEmpty()) {
System.out.println("\nYou must supply the name of cake to bake or "
+ "enter 'exit' to quit!\n");
}
else if (cakeType.toLowerCase().equals("exit")) { System.exit(0); }
else if (!cakeType.toLowerCase().matches("(pound|chocolate|redvelvet)")) {
System.out.println("\nYou must supply the name of cake as shown above!\n");
cakeType = "";
}
}
int desiredSize = 0;
String size = "";
while (size.equals("")) {
System.out.print("\nEnter desired size of cake to be baked (must be at "
+ "least 12\"): -> ");
size = scan.nextLine();
if (size.isEmpty()) {
System.out.println("\nYou must supply the size of cake to bake or "
+ "enter 'exit' to quit!\n");
}
else if (size.toLowerCase().equals("exit")) { System.exit(0); }
else if (Integer.valueOf(size.replace("\"","")) < 12 ) {
System.out.println("\nYou must supply a cake size of 12\" or greater!\n");
size = "";
}
}
desiredSize = Integer.valueOf(size.replace("\"",""));
createCake(cakeType, desiredSize, 0);
}
public static void createCake(String cake, int desiredSize, int currentSize) {
//currentSize is the current amount of batter in the pan
while (currentSize < desiredSize) {
currentSize+= getBatter(cake, desiredSize);
System.out.println(currentSize);
}
System.exit(0); // Done! - Quit!
}
public static int getBatter(String cake, int desiredSize) {
Random gen = new Random(System.currentTimeMillis());
// Since the random generation for the batter amount is the
// same for all cake types according to your code we just
// need this:
int batterAmount = gen.nextInt(3)+6;
// But if we want to be more specific for each Cake Type
// then we can do it this way but first create the required
// batter equations for each cake type and remove the /* and
// */ from the code but first comment out (//) the batterAmount
// variable declaration above.
// NOTE: Both cake diameter AND 'Height' should play into the factor
// of how much batter is required unless of course all cakes made are
// of the same height.
/*
int batterAmount = 0;
switch (cake.toLowerCase()) {
case "pound":
batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
break;
case "chocolate":
batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
break;
case "redvelvet":
batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
break;
} */
return batterAmount;
}
}
Well, I do hope this has helped you somewhat or at least thrown a little thought into the oven :P

Java - error: constructor "constructor name" in class "class name" cannot be applied to given types;

Before asking my question I want to make some things clear. First, I am new to Java and programming in general. Second, This is my first post so please go easy on me if I did something wrong. Finally, I DO NOT want any specific solutions to my assignment in any responses to this post. Those issues are for me to figure out. What I do want is an explanation as to why my test code wont compile/run. To better understand the issue I will paste the assignment information, then the Driver class that is given, then my class code that is accessed by the Driver class. The compiler error I have is shown in the title, but since it is fairly vague, here is a screenshot of the exact errors I'm getting.
The following is the assignment:
You are to design a class “LostPuppy.java” which represents a puppy lost in a multi-floor building that
contains the same number of rooms on each floor. During instantiation (or creation) of an object of this class,
each room on each floor will be initialized as empty (you will actually use the space ‘ ‘ character for this
purpose) and a random room will be chosen where the puppy is lost. For this purpose, the character “P” will
be placed in this random location. Further details on the constructor is listed below.
An object of this class is used as a game for two players to take turns searching for the puppy, one room at a
time until the unfortunate little canine is found. The instantiation of this object and the search will be performed
by a “driver” program which has been provided to you allowing you to only have to concentrate on developing
the class (the driver program is in the file “PuppyPlay.java”)
Fields (of course, all fields are private):
A character (char) array named myHidingPlaces. This represents the building where the rows are floors
and the columns are rooms on each floor (this building has an unusual numbering system; the floors and
rooms both start at zero).
Two integers that will hold the floor and room where the puppy is lost, named myFloorLocation and
myRoomLocation.
A char named myWinner which will be assigned the player’s character when a player finds the puppy
(the driver program uses digits ‘1’ and ‘2’ to more clearly distinguish the players from the puppy).
A boolean named myFound which is set to true when the puppy is found.
Constructor:
Receives two integer parameters as the user’s input for the number of floors and rooms of the building
in which the puppy is lost.
The constructor instantiates the 2D array “myHidingPlaces” as a character array with the first parameter
for the rows (theFloors) and the second parameter as the columns (theRooms).
Initialize myHidingPlaces’ cells, each to contain a space ‘ ‘ (done with single quotes)
Set myFloorLocation (floor puppy is on) randomly based using the first parameter
Set myRoomLocation (room puppy is in) randomly based using the second parameter
Set myHidingPlaces[myFloorLocation][myRoomLocation] to the char ‘P’
Set myWinner to a single space
Set myFound to false
Methods:
roomSearchedAlready receives the floor and room to be searched and returns true if the room has
already been searched, false otherwise.
puppyLocation receives the floor and room to be searched and returns true if the floor and room are
where the puppy is lost, false otherwise. This method should NOT change any of the fields.
indicesOK receives the floor and room to be searched and returns true if the floor and room values are
within the array indices range, false otherwise (used to check that these indices will not cause an error
when applied to the array).
numberOfFloors returns how many floors are in the building (the first floor starts at zero).
numberOfRooms returns how many rooms are on each floor of the building (the first room starts at
zero and all floors have the same number of rooms).
searchRoom receives the floor and room to be searched and also the current player (as a char type)
and returns true if the puppy is found, false otherwise. If the puppy is NOT found searchRoom also
sets the myHidingPlaces array at the received floor and room location to the received player value (a ‘1’
or a ‘2’) OR, when found, sets the myWinner field to the current player AND sets myFound to true.
toString displays the current hidingPlaces array and it’s contents EXCEPT the location of the puppy
which remains hidden until he/she is found at which point toString will be called (by the driver) and both
the player who found the puppy and a ‘P’ will be displayed in the same cell….
NOW, and perhaps the awkward portion of the toString output. Normally, when displaying a 2D array,
the [0][0] cell is displayed in the upper left corner as with matrices. However, because the puppy
decided to get lost in a building and not a matrix, it would make more visual sense to have the first floor
(row 0) displayed on the bottom, second floor above it… and finally the top floor, well… on top! To
save words, look closely at the sample run provided on the next page. Your output should look the
same as what is seen on the next page in the sample run.
Here is the Driver program:
import java.util.Random;
import java.util.Scanner;
/**
* This program is used as a driver program to play the game from the
* class LostPuppy. Not to be used for grading!
*
* A puppy is lost in a multi-floor building represented in the class
* LostPuppy.class. Two players will take turns searching the building
* by selecting a floor and a room where the puppy might be.
*
* #author David Schuessler
* #version Spring 2015
*/
public class PuppyPlay
{
/**
* Driver program to play LostPuppy.
*
* #param theArgs may contain file names in an array of type String
*/
public static void main(String[] theArgs)
{
Scanner s = new Scanner(System.in);
LostPuppy game;
int totalFloors;
int totalRooms;
int floor;
int room;
char[] players = {'1', '2'};
int playerIndex;
boolean found = false;
Random rand = new Random();
do
{
System.out.print("To find the puppy, we need to know:\n"
+ "\tHow many floors are in the building\n"
+ "\tHow many rooms are on the floors\n\n"
+ " Please enter the number of floors: ");
totalFloors = s.nextInt();
System.out.print("Please enter the number of rooms on the floors: ");
totalRooms = s.nextInt();
s.nextLine(); // Consume previous newline character
// Start the game: Create a LostPuppy object:
game = new LostPuppy(totalFloors, totalRooms);
// Pick starting player
playerIndex = rand.nextInt(2);
System.out.println("\nFloor and room numbers start at zero '0'");
do
{
do
{
System.out.println("\nPlayer " + players[playerIndex]
+ ", enter floor and room to search separated by a space: ");
floor = s.nextInt();
room = s.nextInt();
//for testing, use random generation of floor and room
//floor = rand.nextInt(totalFloors);
//room = rand.nextInt(totalRooms);
} while (!game.indicesOK(floor, room)
|| game.roomSearchedAlready(floor, room));
found = game.searchRoom(floor, room, players[playerIndex]);
playerIndex = (playerIndex + 1) % 2;
System.out.println("\n[" + floor + "], [" + room + "]");
System.out.println(game.toString());
s.nextLine();
} while (!found);
playerIndex = (playerIndex + 1) % 2;
System.out.println("Great job player " + players[playerIndex] +"!");
System.out.println("Would you like to find another puppy [Y/N]? ");
}
while (s.nextLine().equalsIgnoreCase("Y"));
}
}
Finally, here is my test code:
import java.util.Random;
import java.util.Scanner;
public class LostPuppy
{
char[][] myHidingPlaces;
int myFloorLocation;
int myRoomLocation;
char myWinner;
boolean myFound;
Random random = new Random();
public void LostPuppy(int theFloors, int theRooms)
{// this ^ void is the issue and is now removed from my code(answered 7/14/2015 on stack overflow)
char[][] myHidingPlaces = new char[theFloors][theRooms];
for (int i = 0; i < theFloors; i++)
{
for (int j = 0; j < theRooms; j++)
{
myHidingPlaces[i][j] = ' ';
}
}
myFloorLocation = random.nextInt(theFloors);
myRoomLocation = random.nextInt(theRooms);
myHidingPlaces[myFloorLocation][myRoomLocation] = 'P';
myWinner = ' ';
myFound = false;
}
public boolean roomSearchedAlready(int floor, int room)
{
if (myHidingPlaces[floor][room] == '1' ||
myHidingPlaces[floor][room] == '2')
{
return true;
}
else
{
return false;
}
}
public boolean puppyLocation(int floor, int room)
{
if (myHidingPlaces[floor][room] == 'P')
{
return true;
}
else
{
return false;
}
}
public boolean indicesOK(int floor, int room)
{
if (floor <= myHidingPlaces.length || room <= myHidingPlaces[0].length)
{
return true;
}
else
{
return false;
}
}
public int numberOfFloors()
{
return myHidingPlaces.length - 1;
}
public int numberOfRooms()
{
return myHidingPlaces[0].length - 1;
}
public boolean searchRoom(int floor, int room, char player)
{
if (myFound = true)
{
myWinner = player;
myFound = true;
return true;
}
else
{
myHidingPlaces[floor][room] = player;
return false;
}
}
public String toString()
{
return "this is a test";
}
}
I DO NOT want any specific solutions to my assignment in any responses
to this post. Those issues are for me to figure out. What I do want is
an explanation as to why my test code wont compile/run.
This line
game = new LostPuppy(totalFloors, totalRooms);
Won't compile because you haven't defined any constructor that expect two int as arguments (totalFloors and totalRooms).
In order to fix this, declare in your class LostPuppy a constructor such as
public LostPuppy(int totalFloors, int totalRooms)
{
//Do something here with paremeters..
}
This line
while (!game.indicesOK(floor, room)
Won't compile because you haven't defined any indicesOk method in your LostPuppy class.
Create a method such as
public boolean indicesOK(int floot, int room)
{
//return some conditions
}
I think your building method should be constructor:
public LostPuppy(int theFloors, int theRooms)
{
myHidingPlaces = new char[theFloors][theRooms]; //this line
for (int i = 0; i < theFloors; i++)
{
for (int j = 0; j < theRooms; j++)
{
myHidingPlaces[i][j] = ' ';
}
}
myFloorLocation = random.nextInt(theFloors);
myRoomLocation = random.nextInt(theRooms);
myHidingPlaces[myFloorLocation][myRoomLocation] = 'P';
myWinner = ' ';
myFound = false;
}
Note: look at the marked line, do not define type, if you define type, it becomes local variable instead of instance variable.

Java TicTacToe - comparing lots of values

I am writing this TicTacToe game. We all know how TicTacToe works, either somebody wins or nobody wins and the board gets full.
board.playable() checks to see if somebody has won the game or if the board is full. This code runs fine but I'm just wondering if there is a tidier way to write my while loop. It just seems a bit redundant to have the same condition twice. But I need to run the board.playable() check before the computer makes his move.
public void runGame()
{
while(board.playable()==true)
{
// Outputs a visual representation to console window
this.displayBoard();
// Asks player to enter a valid number
this.playerMove();
// Check if it still playable for the next
if(board.playable() == true)
{
computerMove()
}
}
this.displayBoard();
// Outputs the final status of the game and the winner if any
if(board.wonBoard()==true) {
System.out.println(board.whoWon() + " has won the game");
} else {
System.out.println("The board is full. Nobody has won the game");
}
}
Your program doesn't seem to have a "turn" state. If it had such an entity, then it could play a turn and check for winner after each turn. Also, get rid of == true in all of your code.
while (gameNotOver) {
// assuming an enum called Turn
if (turn == Turn.PLAYER) {
doPlayersTurn();
} else {
doComputerTurn();
}
checkForWin();
turn = turn.nextTurn();
}
while(board.playable())
{
// Outputs a visual representation to console window
this.displayBoard();
// Asks player to enter a valid number
this.playerMove();
// Check if it still playable for the next
if(board.playable())
{
computerMove();
}
}
remove ==true
You can use the flag to know whose move is : Like this
boolean playerTurn = Boolean.TRUE;
while(board.playable()==true)
{
// Outputs a visual representation to console window
this.displayBoard();
// Asks player to enter a valid number
if(playerTurn){
this.playerMove();
playerTurn=Boolean.FALSE;
}
else{
computerMove();
playerTurn = Boolean.TRUE;
}
}

Having a hard time determining the starting point of my design

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")

Categories

Resources