I am a beginner programmer and i understand this pseudocode will have many errors, and that is why i came here to ask for help! I know i'm not passing anything i just can't seem to wrap my head around how to get them there. I'm also not sure if while gather input i'm using alter and prompt correctly. In the display function, the spacing is necessary for when it will be displayed. Corrections and explanations are greatly appreciated. Any help would be amazing as i cannot wrap my head around how to formulate this. (NOTE: this is for java)
Instructions for exercise:
Last year, a local college implemented rooftop gardens as a way to promote energy efficiency and save money. Write a program that will allow the user to enter the energy bills from January to June prior to going green. Next, allow the user to enter the energy bills from January to June after going green. The program should calculate the energy difference and display the 6 months’ worth of data, along with the savings.
Hint:
Create 4 global arrays of size 6 each. The first array (notGreenCost) will store the first 6 months of energy costs, the second array (goneGreenCost) will store the 6 months after going green, and the third array (savings) will store the difference. Also, create an array (months) that stores the month names
The pseudocode so far:
//Add statements to declare the global array variables
Declare Real notGreenCost[6]
Declare Real goneGreenCost[6]
Declare Real savings[6]
Declare Real months[6]
Module main()
//Declare local variables
Declare String endProgram = “no”
Call initMonths()
While endProgram == “no”
//Module calls
Call getNotGreen()
Call getGoneGreen()
Call energySaved()
Call displayInfo()
Display “Do you want to end the program (enter yes or no):”
Input endProgram
While endProgram<>”no” AND endProgram<>”yes”
Display “Please enter a value of yes or no: ”
Input endProgram
End While
End While
End Module
Module initMonths()
months = “January”, “February”, “March”, “April”, “May”, “June”
End Module
Module getNotGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Display “Enter NOT GREEN energy costs for”, months[counter]
Input notGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module getGoneGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Input goneGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module energySaved()
//Add statements to calculate 6 months of savings and save to the array
Set counter = 0
While counter < 6
Set savings[counter] = notGreenCost[counter] – goneGreenCost[counter]
Set counter = counter + 1
End While
End Module
Module displayInfo()
//Add statements to display results as shown above
Set counter = 0
While counter < 6
Display “Information for”, months[counter]
Display “Savings $”, savings[counter]
Display “Not Green Costs $”, notGreenCost[counter]
Display “Gone Green Costs $”, goneGreenCost[counter]
End While
End Module
Perhaps this is what you are looking for
import java.util.Scanner;
class A{
public static int []PriorGreen = new int[6];
public static int []AfterGreen = new int[6];
public static String []month = {"Jan","Feb","Mar","April","May","June"};
static void PriorG()
{
System.out.println(" Enter Cost for Prior Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
PriorGreen[i]=in.nextInt();
}
}
static void AfterG()
{
System.out.println(" Enter Cost for After Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
AfterGreen[i]=in.nextInt();
}
}
static void energySaved()
{
for(int i=0;i<6;i++){
System.out.println(" Energy saved in "+month[i]+" is "+(PriorGreen[i]-AfterGreen[i]));
}
}
static void display()
{
System.out.println("Prior Green "+"After Green "+ "Savings");
for(int i=0;i<6;i++){
System.out.println(PriorGreen[i]+" "+AfterGreen[i]+" "+(PriorGreen[i]-AfterGreen[i]));
}
}
public static void main(String []args)
{
PriorG();
AfterG();
energySaved();
display();
}
}
I see only one small oversight in your pseudocode. In your displayInfo you forgot to increment your counter. You should add Set counter = counter + 1 inside the while loop.
One other thing I notice is that you have a loop that runs the core logic until the user responds "no":
While endProgram == “no” which is not in your requirements. I don't think it's a bad thing necessarily but it would depend on your instructor and whether they would mark you down for that.
I suggest you start writing your Java code and update your post if you run into problems for which you can't find a solution.
I'm fairly new to java and am experimenting building my own text based game, at the moment im just trying to work on individual concepts and then hopefully be able to pull it all together in a final project, my problem i have come across at the moment and cant seem to find an answer is exactly what the title question states:
How can i validate user input against a String ArrayList of randomly generated elements?
To clarify, i have a working program at the moment that when run generates a random amount and random types of enemy and then populates them into the dungeon each time the dungeon object is created, the user is then presented with a question allowing them to pick which enemy they should confront first, this is where i require the validation in order that the game would continue, im trying to use a while loop which if the condition returns false would just skip and move on to if statements and their validations, i hope that makes sense and ive posted my code below, apologies in advance if there are many things wrong with my code either syntactically or structurally as stated earlier im still very new to java and at the moment if i can just learn to code then i can worry about how professional or proper something should be.
Here is my code:
package com.davegreen;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
// Declaring some variables and creating some objects of other classes that i need.
Scanner scanner = new Scanner(System.in);
Dungeon dungeon = new Dungeon();
List<String> enemyType = dungeon.getEnemy(); // Gets all the enemy from my enemy ArrayList in the Dungeon class.
int enemyNumberTotal = dungeon.getEnemy().size(); // Gets the amount of enemy in my enemy ArrayList.
runGame();
int randomAmountOfEnemy = generateRandomNumber(enemyNumberTotal); // Generates a random amount of enemy into the dungeon from the total number in the ArrayList.
System.out.println("\n The enemies in this dungeon are: \n");
// Generates the random enemies that will populate the dungeon based on a method in my Dungeon class and then passes a random amount of said enemy each time also.
List<String> randomlyPickedEnemy = dungeon.populateWithRandomEnemy(enemyType, randomAmountOfEnemy);
System.out.println("\n\t * " + randomlyPickedEnemy);
System.out.println("\n> Which enemy would you like to confront first?");
String userChoice = scanner.nextLine();
// I want to validate the user input from line 31 of the code to reflect that if the user has not selected an enemy that was in the randomly populated list
// then we stay in the while loop and continue asking until of course the user types in a enemy that was in the randomly populated list, at which
// point we would of course skip the while loop moving onto the if statements validation, it would be nice also to have ignore case somewhere in there.
while(!userChoice.equals(randomlyPickedEnemy))
{
System.out.println("\n\t That enemy does not live in this dungeon!");
System.out.println("\n> Which enemy would you like to confront first?");
userChoice = scanner.nextLine();
}
// For the validation here i realise of course that just using the variable randomlyPickedEnemy in the sout would more than likely return ALL the enemy that
// were randomly populated and not specifically the enemy that the user had chosen, so at this point i need a way to be able to access exactly what enemy it was
// that the user had chosen to battle so that the sout statement makes sense but more importantly so i can then direct the code where it needs to go based on any given
// particular enemy.
if(userChoice.equals(randomlyPickedEnemy))
{
System.out.println("You have chose to battle " + randomlyPickedEnemy);
}
}
public static void runGame()
{
System.out.println("##################################################");
System.out.println("##### DUNGEON CRAWLER #####");
System.out.println("##################################################");
}
// This is my method to generate a random amount of enemy for the total amount of enemy in my ArrayList.
public static int generateRandomNumber(int howManyEnemies)
{
Random random = new Random();
int rng = random.nextInt(howManyEnemies) + 1;
System.out.println("\n There are " + rng + " enemies in this dungeon!");
return rng;
}
}
You are actually comparing a String to a List (randomlyPickedEnemy).
If I understand correctly, you want to know if this list contains the input of the user.
To do this you just have to modify your whilestatement :
while(!randomlyPickedEnemy.contains(userChoice)) {
...
}
so I've been studying Java for about 3 months and I am supposed to do a Hangman code using only arrays, loops, and if statements. the word to be guesses is read from another file and saved as a string. I have to be able to save the wrong guesses in an array. and after each guess print all the wrong guesses so far, as well as the gameboard with underscores for not guessed letters and the correct guesses of course in their place. here is my code so far :
for(int l = 0; l<wordlength;l++)
{
System.out.print("_");
}
System.out.println();
System.out.println("WRONG: ");
for(int c = 0; c<numofGuesses;c++)
{
System.out.println();
System.out.print("GUESS"+guessN+"/"+numofGuesses+": ");
char guess1=in.next().charAt(0);
char guess = Character.toUpperCase(guess1);
guessN = guessN+1;
for (int j = 0; j<wordlength;j++)
{
if (guess==guessword.charAt(j))
{
System.out.println("Great guess!");
System.out.print (guessword.charAt(j));
}
else
{
System.out.print("_");
WRONG[u]=guess;
u++;
}
}
if you guess A it prints correctly "A___" but then if you guess B after instead of printing "AB__" (the word to guess is ABLE) i get "B__" also the wrong array is not storing and printing all the wrong guesses each time. please help I've been trying for 5 days and that's all I did the entire day today and I couldn't get past this.
Because this sounds a lot like a homework assignment, I will give directions for solving this, but not provide a full working solution. Hopefully, seeing how one could1 go about approaching such a problem is enough of a step in the right direction to be able to solve it yourself.
Let's first think about what we need to do.
Read a word that needs to be guessed, say String toBeGuessed.
You did this. ✔
Keep track of the characters the player has guessed so far.
Keep track of the number of turns a player has gotten.
Keep track of if the word has been guessed (player won!).
Say that the number of guesses a player can make is fixed. This can be modeled using a constant:
/**
* Number of guesses a player can take.
*/
public static final int NUM_GUESSES = 10;
Now let's think about the main logic of our hangman game. It is good to first think about the structure of your program and only later actually implement it. When thinking of the program structure, we don't bother with specifics of the programming language of your choice yet. In pseudocode, it would be something like the following, maybe (let's indicate what you already have with ✔).
for turn from 1 upto NUM_GUESSES do ✔
show player what they guessed so far
show the gameboard
ask player for their new guess ✔
save player's guess and update internal state
check if the player won, let them know if they did
if player did not win
let them know
Right. So, we need to somehow store the guesses that a player made. Every guess is a character, and we know there will be at most NUM_GUESS guesses in total. A good option (and one that is suggested by your exercise) is an array!
/**
* Characters that have been guessed so far.
*/
private char[] guessed;
This can be initialized as follows, since we know the maximum number of guesses:
this.guessed = new char[NUM_GUESSES];
This gives us an array of NUM_GUESSES characters that are initialized to 0 (see here). Since users won't guess that character, we can use it to represent guesses that have not been done yet. Alternatively, we can keep track of the current turn of the player in a separate variable. Your choice!
In the following, I will not keep track of the current turn in a separate variable, just to show more of arrays and loops. It might be a fun exercise to change this to using an int turn variable!
show player what they guessed so far
Alright, this should be fairly straightforward now. We basically need to print the part of the guessed array that is not 0. That can be done using a loop, like so for example:
System.out.print("You so far guessed: ");
for (int i = 0; i < guessed.length; ++i) {
if (i > 0) {
System.out.print(", ");
}
if (guessed[i] != 0) {
System.out.print(guessed[i]);
} else {
break; // stop the loop as soon as we run into a 0
}
}
System.out.println(".");
This will print something like You so far guessed: a, b, c. when the player guessed those characters. See how we only print the comma when some other character was printed before?
show the gameboard
The next point of the program structure is trickier to get right. Let's think a bit about structure again.
for each character in toBeGuessed
if the character has been guessed
print it
else
print an underscore
Looping over every character of a word can be done as follows.
int length = toBeGuessed.length();
for (int i = 0; i < length; ++i) {
char character = toBeGuessed.charAt(i);
// do something with character here
}
How do you find if a character has been guessed yet? Well, by checking if it is stored in the guessed array. This again can be done using a loop. That loop will be very similar to the one we have written above, when showing what the player guessed so far. I think you should be able to figure that one out.
save player's guess and update internal state
We move on to the next point of the program structure. Say that we have a char guess that the player guessed. We need to store this in our array guessed. Where? Well, at the first open spot, that seems a reasonable choice. To find that one, let's use a loop again, and break the loop when we have found an open spot.
for (int i = 0; i < guessed.length; ++i) {
if (guessed[i] == 0) {
guessed[i] = guess;
break;
}
}
check if the player won, let them know if they did
What we need to know in order to see if the player won, is simply if the number of characters they guessed right is equal to the number of characters in toBeGuessed. You could modify the loop for showing the gameboard to not print characters, but count correct ones. Then at the end compare to toBeGuessed.length() and if they are equal, the player won.
if player did not win, let them know
This should be fairly easy, if you got the previous point working.
When you did all the above and stitched it together, you should have a working version of hangman. Your very own, something to be proud of!
Some tips and tricks:
you can implement most of the points described above as separate methods;
when you do so, you can write one main method that calls the other methods (this will make it easier to read your own code and make changes to it);
try to put as little code as possible in the main method.
Here is a little template that you can start from.
import java.io.PrintStream;
import java.util.Scanner;
public class HangMan
{
/** Number of guesses a player can take. */
public static final int NUM_GUESSES = 10;
/** Word to be guessed in a game of hangman. */
private String toGuess;
/** Letters that have been guessed so far. */
private char[] guessed;
/**
* Construct a new game of hangman, ready to be played.
*/
public HangMan(String toGuess)
{
this.toGuess = toGuess;
this.guessed = new char[NUM_GUESSES];
}
// your other methods go here
/**
* Read guesses from given input and print results to given output.
* Continues until guesses have run out, or word was guessed.
*/
public void play(Scanner in, PrintStream out)
{
for (int round = 0; round < NUM_GUESSES; ++round) {
showGuessedSoFar(out);
showGameBoard(out);
char guess = askGuess(in, out);
saveGuess(guess);
if (hasPlayerWon()) {
out.println("You won!");
return;
}
}
// at this point, player ran out of guesses and hence lost
out.println("You lost...");
}
/**
* The bit that runs our hangman game.
*/
public static void main(String[] args)
{
// read word to guess from arguments, with a default value
// you would probably insert your "read word from file" code here
HangMan game = new HangMan(args.length >= 1 ? args[0] : "ABLE");
// play a game, using system input and output
game.play(new Scanner(System.in), System.out);
}
}
Good luck!
TL;DR. Trying to teach one how to think about a problem and how to write code that executes the solution one thought of. Features some example code with arrays and loops.
1 This is only one possible solution, there are always many ways to solve a given problem.
The requirements of the program are:
Antonia and David are playing a game.
Each player starts with 100 points.
The game uses standard six-sided dice and is played in rounds. During one round, each player rolls one die. The player with the lower roll loses the number of points shown on the higher die. If both players roll the same number, no points are lost by either player.
Write a program to determine the final scores.
I came up with the following code:
import java.util.*;
public class prob3
{
public static void main(String[]args)
{
Random g=new Random();
int a,b,c;
int rounds;
int antonio=100;
int david=100;
Scanner s=new Scanner(System.in);
System.out.println("Please enter the no. of rounds you want to play(1-15): ");
rounds=s.nextInt();
for(int d=1;d<=rounds;d++)
{
a=g.nextInt(6)+1;
b=g.nextInt(6)+1;
System.out.println("Round "+d+":"+a+" "+b);
if(a<b)
antonio=100-b;
else if(a>b)
david=100-a;
}
System.out.println("Total for Antonio: "+antonio);
System.out.println("Total for David: "+david);
}
}
The program fails to calculate the right sum at the end.
What am I doing wrong?
Any help would be appreciated.
Thanks.
You are doing this.
antonio=100-b;
When you probably want
antonio = antonio - b;
The first code simply subtracts the dice roll from 100 every time, which is pointless. You want to subtract the dice roll from the players totals. Do this for both players.
As stated above the "100 - b" was your main problem. But there is no reason in your problem statement to set a number of rounds.
I whould rather use a loop like this:
while(antonio >= 0 && david >= 0){
//do the same stuff here
}
System.out.println...
Since it looks as some exercise for some java course.. This may sound useless but:
Format always your code.. Spaces, brakets and tabs
Use descriptive variable mames. a b c d are not quite intuitive in a larger program.
Remover unused variables
Y mucha suerte tío!
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")