I'm making my first text adventure game with C#, and I was just wondering how I would loop back to a previous if statement.
For Example:
if (x == 2 || y == 3)
{
//do this
if ( z > 3 || v = 6)
{
//do this
}
}
What would I use to make it go from the nested if, to the top if statement?
EDIT: more specifically:
//start
System.Console.WriteLine("You awake in a stupor. The sun blinds you as you roll over to breathe the new day.");
System.Console.WriteLine(" ");
System.Console.WriteLine(" ");
System.Console.WriteLine("To your (west), you see a volcanic mountain, with a scraggly, dangerous looking path.");
System.Console.WriteLine(" ");
System.Console.WriteLine("In the (east), you see a thick forrest. there is nothing visible past the treeline.");
System.Console.WriteLine(" ");
System.Console.WriteLine("Looking (south), you see a long winding road that seems to have no end.");
System.Console.WriteLine(" ");
System.Console.WriteLine("Hearing a sound of celebration, you look to the (north). There appears to be a city, with a celebration going on.");
System.Console.WriteLine(" ");
System.Console.WriteLine(" ");
System.Console.WriteLine("Which direction would you like to travel?");
string direction1 = Convert.ToString(Console.ReadLine());
//first decision (north)
if (direction1 == "north" || direction1 == "North")
{
Console.WriteLine("You proceed towards the north, only to be stopped by a guard:");
Console.WriteLine("Guard: 'the kingdom of al'arthar is off limits to outsiders today, its the queens birthday, and the kingdom is packed full");
Console.WriteLine(" ");
Console.WriteLine(" ");
Console.WriteLine("you can either try to (swindle) the guard, or (leave). What will you do?");
string guardConvo1 = Convert.ToString(Console.ReadLine());
Say, for example, if someone traveled North in this scenario, and then wanted to go back. Rather than recode the previous if statement, how would I make it just loop back to the previous if statement?
It's hard to know without knowing more context about what you're trying to do. You might want to extract some code into its own method and call it in both places, or create a loop (for, while, etc.) to handle control. It's even possible to use a goto command, though I would almost never recommend that.
Maybe you should have some sort of state machine running your game to help handle conditions and actions.
Update: As you've found, the way you're writing the code is almost entirely unworkable for a text adventure game. Something to get you going in the right direction would be this: refactor each room into its own method. When you want to go from one room to another, you call the method for that room.
void StartingArea()
{
System.Console.WriteLine("You awake in a stupor. The sun blinds you as you roll over to breathe the new day.");
System.Console.WriteLine(" ");
System.Console.WriteLine(" ");
System.Console.WriteLine("To your (west), you see a volcanic mountain, with a scraggly, dangerous looking path.");
System.Console.WriteLine(" ");
System.Console.WriteLine("In the (east), you see a thick forrest. there is nothing visible past the treeline.");
System.Console.WriteLine(" ");
System.Console.WriteLine("Looking (south), you see a long winding road that seems to have no end.");
System.Console.WriteLine(" ");
System.Console.WriteLine("Hearing a sound of celebration, you look to the (north). There appears to be a city, with a celebration going on.");
System.Console.WriteLine(" ");
System.Console.WriteLine(" ");
System.Console.WriteLine("Which direction would you like to travel?");
string direction1 = Convert.ToString(Console.ReadLine());
if (direction1 == "north" || direction1 == "North")
{
AlArtharGate();
}
}
void AlArtharGate()
{
Console.WriteLine("You proceed towards the north, only to be stopped by a guard:");
Console.WriteLine("Guard: 'the kingdom of al'arthar is off limits to outsiders today, its the queens birthday, and the kingdom is packed full");
Console.WriteLine(" ");
Console.WriteLine(" ");
Console.WriteLine("you can either try to (swindle) the guard, or (leave). What will you do?");
string guardConvo1 = Convert.ToString(Console.ReadLine());
if (string.Equals(guardConvo1, "leave", StringComparison.CurrentCultureIgnoreCase))
{
StartingArea();
}
}
This isn't perfect, but it's better: you have made each area its own callable entity instead of just a section of code in an if statement. You can study the code of this Python text adventure game base for a more advanced and complete example.
By the way, you might want to be ignoring all case (like I did with the comparison at the end), not just checking for "north" and "North".
Hmm not much to go on here, but there are a lot of things you could do.
A State machine is mentioned, but it might be a little abstract to wrap around at first. But think of it as cities and roads, you as a person can be at one place and only walk one road at a time. Sometimes you end up going in circles, other times you reach the end.
In your game you have a lot of actions or we can call them choices if you like. and maybe this pseudocode might get you on the right track of mind.
void Init(){
Print("Select Choice")
int choice = Read()
if(choice == 1)
{
Choice1()
}
else if(choice == 2)
{
Choice2()
}
else
{
InvalidChoice()
}
}
void Choice1(){
Print("Welcome to Choice1 perform action or choice")
int choice = Read()
if(choice == 1)
{
Choice2()
}
else if(choice == 2)
{
Choice3()
}
else
{
InvalidChoice()
}
}
void Choice2(){
Print("Welcome to Choice2 perform action or choice")
int choice = Read()
if(choice == 1)
{
Choice3()
}
else if(choice == 2)
{
Choice1()
}
else
{
InvalidChoice()
}
}
void Choice3()
{
InvalidChoice()
}
void InvalidChoice()
{
Print("You died")
}
Related
Hello I am trying to figure out why my program is not working, it's supposed to output a program in which department codes would be entered and followed by a prompt to enter a mark and so on until Q is entered. I can't seem to get that part working at all. If anyone could help please I will appreciate it.
// declare variables
char deptCode = ' ';
int count = 0;
double markVal, sum = 0, average = 0.0;
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
while (char.ToUpper(deptCode) != 'Q')
do
{
Console.Write("Enter a mark between 0 and 100 => ");
markVal = Convert.ToDouble(Console.ReadLine());
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
} while (markVal >= 0 && markVal <= 100);
count++;
average = (double)sum / count;
Console.WriteLine("***Error, Please Enter Valid Mark");
Console.WriteLine("The Average mark for Computer Science Students is {0}", average);
Console.WriteLine("The Average mark for Biology Students is {0}", average);
Console.WriteLine("The Average mark for Physics Students is {0}", average);
Console.ReadLine();
{
I am sympathetic to your dilemma and know it can be challenging to learn coding when you are not familiar with it. So hopefully the suggestions below may help to get you started at least down the right path. At the bottom of this is a basic “shell” but parts are missing and hopefully you will be able to fill in the missing parts.
One idea that you will find very helpful is if you break things down into pieces (methods) that will make things easier to follow and manage. In this particular case, you need to get a handle on the endless loops that you will be creating. From what I can see there would be three (3) possible endless loops that you will need to manage.
An endless loop that lets the user enter any number of discipline marks.
An endless loop when we ask the user which discipline to use
And an endless loop when we ask the user for a Mark between 0 and 100
When I say endless loop I mean that when we ask the user for a Discipline or a Mark… then, the user MUST press the “c”, “b” “p” or “q” character to exit the discipline loop. In addition the user MUST enter a valid double value between 0 and 100 to exit the Mark loop. The first endless loop will run allowing the user to enter multiple disciplines and marks and will not exit until the user presses the q character when selecting a discipline.
And finally when the user presses the ‘q’ character, then we can output the averages.
So to help… I will create two methods for you. One that will represent the endless loop for getting the Mark from the user… i.e.…. a number between 0 and 100. Then a second endless loop method that will get the Discipline from the user… i.e. … ‘c’, ‘b’, ‘p’ or ‘q’… and it may look something like…
private static char GetDisciplineFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a department code: ‘C’ for Computer Science,‘B’ for Biology, ‘P’ for Physics, or enter ‘Q’ to quit:");
userInput = Console.ReadLine().ToLower();
if (userInput.Length > 0) {
if (userInput[0] == 'c' || userInput[0] == 'b' ||
userInput[0] == 'p' || userInput[0] == 'q') {
return userInput[0];
}
}
Console.WriteLine("Invalid discipline => " + userInput + " try again.");
}
}
Note… the loop will never end until the user selects the characters ‘c’, ‘b’, ‘p’ or ‘q’. We can guarantee that when we call the method above, ONLY those characters are returned.
Next is the endless loop to get the Mark from the user and may look something like…
private static double GetMarkFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a mark between 0 and 100 => ");
userInput = Console.ReadLine().Trim();
if (double.TryParse(userInput, out double mark)) {
if (mark >= 0 && mark <= 100) {
return mark;
}
}
Console.WriteLine("Invalid Mark => " + userInput + " try again.");
}
}
Similar to the previous method, and one difference is we want to make sure that the user enters a valid number between 0 and 100. This is done using a TryParse method and most numeric types have a TryParse method and I highly recommend you get familiar with it when checking for valid numeric input.
These two methods should come in handy and simplify the main code. So your next issue which I will leave to you, is how are you going to store these values? When the user enters a CS 89 mark… how are you going to store this info? In this simple case… six variables may work like…
int totalsCSMarks = 0;
int totalsBiologyMarks = 0;
int totalsPhysicsMarks = 0;
double totalOfAllCSMarks = 0;
double totalOfAllBiologyMarks = 0;
double totalOfAllPhysicsMarks = 0;
Now you have something to store the users input in.
And finally the shell that would work using the methods above and you should see this uncomplicates things a bit in comparison to your current code. Hopefully you should be able to fill in the missing parts. Good Luck.
static void Main(string[] args) {
// you will need some kind of storage for each discipline.. see above...
char currentDiscipline = 'x';
double currentMark;
while (currentDiscipline != 'q') {
currentDiscipline = GetDisciplineFromUser();
if (currentDiscipline != 'q') {
currentMark = GetMarkFromUser();
switch (currentDiscipline) {
case 'c':
// add 1 to total number of CS marks
// add currentMarkValue to the total of CS marks
break;
case 'b':
// add 1 to total number of Biology marks
// add currentMarkValue to the total of Biology marks
break;
default: // <- we know for sure that only p could be left
// add 1 to total number of Physics marks
// add currentMarkValue to the total of Physics marks
break;
}
}
}
Console.WriteLine("Averages ------");
//Console.WriteLine("The Average mark for Computer Science Students is {0}", totalOfAllCSMarks / totalCSMarks);
//Console.WriteLine("The Average mark for Biology Students is {0}", ...);
//Console.WriteLine("The Average mark for Physics Students is {0}", ...);
Console.ReadLine();
}
I'm a noobie when it comes to programming still, decided I wanted to test my limits and create a tic tac toe game. I'm sure there are much better ways of doing what I'm trying to do but I'm only still learning. When testing what I have so far, I've been running into this problem where a user is asked to input a position (the positions are 1-9, and these positions will eventually be used to tell the program where to put the users X or O). I have 2 classes right now, the Main class and the Board class. After a bit of debugging by putting a stop marker, I've come to realize that when I'm calling a method from my board class in my main class, the data that was put into the arguments for the method isn't carrying over.
Main Class:
class Program {
static void Main(string[] args) {
Board board = new Board();
bool hasWon = false;
string p1;
string p2;
string pos;
int turn = 2;
Console.Write("Please enter a name for player 1: ");
p1 = Console.ReadLine();
Console.Clear();
Console.Write("Please enter a name for player 2: ");
p2 = Console.ReadLine();
Console.Clear();
while (hasWon == false) {
if (turn % 2 == 0) {
Console.WriteLine(p1 + "'s Turn / You are X's");
board.DisplayBoard();
Console.WriteLine();
Console.WriteLine("Please selecet a position: ");
board.SetPos(Console.ReadLine());
Console.WriteLine("Position correctly set: " + board.GetPos());
} else {
Console.WriteLine(p2 + "'s Turn / You are O's");
board.DisplayBoard();
Console.WriteLine();
Console.WriteLine("Please selecet a position: ");
board.SetPos(Console.ReadLine());
Console.WriteLine("Position correctly set: " + board.GetPos());
}
}
}
}
Board Class:
public class Board {
private string pos = "";
private string badPos = "";
public void DisplayBoard() {
Console.WriteLine(" 1 | 2 | 3 ");
Console.WriteLine("-----------");
Console.WriteLine(" 4 | 5 | 6");
Console.WriteLine("-----------");
Console.WriteLine(" 7 | 8 | 9 ");
}
public void SetPos(string pos) {
if (this.pos.Length > 1 || this.pos.Length < 1) {
this.pos = badPos;
IncorrectPosition();
} else if (!this.pos.Contains("1") || this.pos.Contains("2") || this.pos.Contains("3") || this.pos.Contains("4") ||
this.pos.Contains("5") || this.pos.Contains("6") || this.pos.Contains("7") || this.pos.Contains("8") ||
this.pos.Contains("9")) {
this.pos = badPos;
IncorrectPosition();
} else {
this.pos = pos;
}
}
public string GetPos() {
return pos;
}
/*public void setTurn(int turn) {
turn = this.turn;
}*/
private void IncorrectPosition() {
Console.Clear();
Console.WriteLine(badPos + " is not a correct position");
Console.Write("Please enter a position: ");
SetPos(Console.ReadLine());
}
}
To be more specific, the issue is happening in the Main class. When the user is asked to enter a position, they do so by entering a number 1-9. In the Board class, there is a method called SetPos, which will be used to determine where to place the X or the O later on when I develop that. However, I also have a method that makes sure what the user entered was a number 1-9. I don't want to convert it into an integer, I want it to stay a string. Whenever the user enters anything for the position, nothing gets carried over. When using the stop marker and going through the program step by step, in the watch list where I can see what values are being assigned to what variables, my pos variable does get assigned to what I've inputted, but is then lost thus repeating the SetPos and IncorrectPosition. When the IncorrectPosition is being displayed to the console, it shows
is not a correct position
Please enter a position:
Inside the SetPos() method, I have tried a few things to fix this, one of which being I've added a badPos variable, meaning if any of the first two things in my if statement are true, then the value that was passed through the SetPos() method in my Main class would be assigned to badPos, but when printed out to the console, there is no value being displayed on the screen, which is another way of telling me that no value was ever assigned.
I'm not sure how to fix this issue, and any help would be greatly appreciated, thanks!
public void SetPos(string pos)
{
if (this.pos.Length > 1 || this.pos.Length < 1)
{
// by using "this" you are checking "pos" in the class and not the provided value
// I'll assume that that "badPos" here is a placeholder as this would result in this.pos getting set to null because a variable named badPos has yet to be declared in this scope
this.pos = badPos;
IncorrectPosition();
}
else if (!this.pos.Contains("1") || this.pos.Contains("2")
|| this.pos.Contains("3") || this.pos.Contains("4")
|| this.pos.Contains("5") || this.pos.Contains("6")
|| this.pos.Contains("7") || this.pos.Contains("8")
|| this.pos.Contains("9"))
{
// why not just use an int here? also if I'm reading this correctly 2 through 9 will make this true and then tell the player that this is a bad position.
this.pos = badPos;
IncorrectPosition();
}
else
{
this.pos = pos;
}
}
Here is how I would do it:
public void SetPos(int pos)
{
if (pos > 0 && pos < 10)
{
// when you devise a way to store the board state you would check if the position is occupied here and any other checks you want to do - before assigning the value
this.pos=pos;
}
else
{
this.pos = null;
IncorrectPosition();
}
}
So, I used an int and you said you didn't want to use that - I think you will find when you try to construct a data structure to hold your board state - math will be unavoidable. For you use there is no difference between the string "1" and the int 1 except that one is a lot harder to validate then the other
I digress
The reason your checks always went to "bad position" is that in your first if clause by using 'this' you check if the class's copy of pos.length is greater or less than 1 - as it is null at the time of the check its length is 0 and so the clause returns true.
you need to refer the passed variable by just doing pos without the this in front of it.
I want to set new random values from an Array into a List till one of two conditions is met. But it's only letting me add another 1 value without considering the condition. After I enter "y" the program letting me to get another value and then it asking me again if I want another card, when I enter "y" again , the code move on without letting me add another value.
The second problem is with the if(Hands.playerHand.Sum() > 22) I want the program to calculate the total value of the list and if it's more then 22 then execute the command.
Thank you!
string userAnotherCard = Console.ReadLine();
bool secondHand = true;
secondHand = (userAnotherCard == "y");
bool secondHandNo = true;
secondHandNo = (userAnotherCard == "n");
while(secondHand)
{
//if user want another card, this programm will ganerate another card and store it inside playerHand
Hands.playerHand.Add(Deck.CardDeck[Hands.rando.Next(0, Deck.CardDeck.Length)]);
Console.WriteLine("Your cards are: ");
Hands.playerHand.ForEach(Console.WriteLine);
Console.WriteLine("Would u like to take another card?");
Console.ReadLine();
if(Hands.playerHand.Sum() > 22)
Console.WriteLine("You loss, your cards sum is more than 21");
break;
}
while (secondHandNo)
break;
So I changed the code a little. Now I can choose as many values as I want but I have a problem with the while (secondHandNo) and the while (Hands.playerHand.Sum() > 21) commands. When I enter "n" after taking another card the while (secondHandNo) which should continue the code wont executed. The while (Hands.playerHand.Sum() > 21) doesn't executed as well. It's just giving me more values no matter what my answer is. Note that when I enter "n" right away without taking another card, the command work just fine and it's taking me to the rest of the code.
string userAnotherCard = Console.ReadLine();
bool secondHand = true;
secondHand = (userAnotherCard == "y");
bool secondHandNo = true;
secondHandNo = (userAnotherCard == "n");
while (secondHand)
{
Hands.playerHand.Add(Deck.CardDeck[Hands.rando.Next(0, Deck.CardDeck.Length)]);
Console.WriteLine("Your cards are: ");
Hands.playerHand.ForEach(Console.WriteLine);
Console.WriteLine("Would u like to take another card?");
Console.ReadLine();
}
while (Hands.playerHand.Sum() > 21)
{
Console.WriteLine("You loss, your cards sum is more than 21");
break;
}
while (secondHandNo)
break;
You have quite a few issues here:
You are not storing the result from the console. This can be solve easily:
userAnotherCard = Console.ReadLine();
Even if we stored it, in the while your condition checks a value that was previously assigned and is never changed. This the reason that you are in an endless loop. I would replace it simply with the condition itself:
while (userAnotherCard == "y")
It seems you are using while break instead of a simple if:
if (Hands.playerHand.Sum() > 21)
while (secondHandNo) break; is useless and can be removed from the code.
That should be enough. Final code can look like this:
string userAnotherCard = Console.ReadLine();
while (userAnotherCard == "y")
{
Hands.playerHand.Add(Deck.CardDeck[Hands.rando.Next(0, Deck.CardDeck.Length)]);
Console.WriteLine("Your cards are: ");
Hands.playerHand.ForEach(Console.WriteLine);
Console.WriteLine("Would u like to take another card?");
userAnotherCard = Console.ReadLine();
if (Hands.playerHand.Sum() > 21)
{
Console.WriteLine("You loss, your cards sum is more than 21");
break;
}
}
Ok I was able to fix this block of code. It seems to work now. I set the whole block into while loop and set each condition with an if statement and a break; if condition is met.
while (true)
{
Console.WriteLine("Would u like to take another card?");
string userAnotherCard = Console.ReadLine();
bool secondHand = true;
secondHand = (userAnotherCard == "y");
bool secondHandNo = true;
secondHandNo = (userAnotherCard == "n");
if (secondHand)
{
Hands.playerHand.Add(Deck.CardDeck[Hands.rando.Next(0, Deck.CardDeck.Length)]);
Console.WriteLine("Your cards are: ");
Hands.playerHand.ForEach(Console.WriteLine);
}
if (Hands.playerHand.Sum() > 21)
{
Console.WriteLine("You loss, your cards sum is more than 21");
break;
}
if (secondHandNo)
break;
}
So I'm making a console-based text game to learn more C# but I'm now stuck and have resorted to SO.
This might be an obvious answer but I require another pair of eyes to help me. I've checked the other questions on here and they don't seem to aid me.
In my Main(), I have the following:
int age;
Console.Write("Before entering the unknown, could you please confirm your age? ");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
if (age < 18)
{
Console.WriteLine("I'm sorry, you'll now be transferred to a non-explicit version.");
Console.WriteLine("\n<Press any key to continue>");
Console.ReadKey();
Console.Write("\nPlease wait...");
for (int t = 5; t >= 0; t--)
{
Console.CursorLeft = 22;
Console.Write("{0:00}" + " seconds remaining", t);
Thread.Sleep(1000);
}
Console.WriteLine("");
Console.WriteLine("\nTo proceed, please press any key...");
Console.ReadLine();
NonExplicit();
}
Self explanatory. Once it hits the NonExplicit() method, the following is called:
char yes = Console.ReadKey().KeyChar;
string name;
Console.WriteLine("\nYou're awake? It's about time. Not old enough, eh? That sucks. \n\nListen, I really need your help. Would you be interested? Y / N");
Console.ReadKey();
if (yes == 'y' || yes == 'Y')
{
Console.Write("\nYou will?! Wow, That's fantastic. Right then, where shall I start? \nI know! How about telling me your name? ");
name = Console.ReadKey().ToString();
Console.WriteLine("\nAhh yes, now you mention it, I certainly remember you, {0}!", name);
}
else
{
Console.WriteLine("\nYou don't want to help me? Oh, that's unfortunate... ");
}
What seems to happen is that, when 'y' or 'Y' is pressed:
1) It requires enter to be hit to register the above.
2) It runs both the if & else WriteLines, which I assume is in conjunction with 1)?
How can I amend my code so that when 'y/Y' is pressed, it reads the correct criteria? Or how can I remove the need for Enter to be pressed to proceed?
Used your code below, I tested it and it works.
I moved the char yes = Console.ReadKey() to below the Console.WriteLine().
I changed the name = Console.ReadKey() to Console.ReadLine() because a name is more then 1 key.
string name;
Console.WriteLine("\nYou're awake? It's about time. Not old enough, eh? That sucks. \n\nListen, I really need your help. Would you be interested? Y / N");
char yes = Console.ReadKey();
if (yes == 'y' || yes == 'Y')
{
Console.Write("\nYou will?! Wow, That's fantastic. Right then, where shall I start? \nI know! How about telling me your name? ");
name = Console.ReadLine();
Console.WriteLine("\nAhh yes, now you mention it, I certainly remember you, {0}!", name);
Console.ReadKey(); // I put this here so the program wouldn't exit
}
else
{
Console.WriteLine("\nYou don't want to help me? Oh, that's unfortunate... ");
}
In your code, after Console.WriteLine("\nTo proceed, please press any key..."); you have Console.ReadLine(); which expects you to enter a line in the console (not reading till you press enter) and then in your second method, you're trying to read the console again (but this time for a single key).
Wouldn't it help if you remove the first Console.ReadLine() ?
And then you are trying to get the yes/no answer before asking your question (and before doing another ReadKey.
string result = Console.ReadLine();
if (result.ToUpper().Equals("Y"))
{
//any thing
}
char yes = Console.ReadKey(); // No need for .KeyChar
int age;
Console.Write("Before entering the unknown, could you please confirm your age? ");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
could be
int age = -1
Console.WriteLine("Before entering the unknown, could you please confirm your age? ");
while (age == -1)
{
if !(int.TryParse(Console.ReadLine(), out age))
{
Console.WriteLine("Please enter a valid age");
}
}
name = Console.ReadKey().ToString();
should be
name = Console.ReadLine();
if (yes == 'y' || yes == 'Y')
could be
if (yes.ToUpper() == "Y")
My program collects the number of bottles collected by four rooms. When the user types in quit at anytime, the program goes out of the while look and shows the outcome of the bottle collection. It then calculates the winning room with the most bottle count.
I have a while loop I dont understand why I cant enter it. To enter the while loop, it will prompt me to enter a number 1-4, as used in my array, and the number of bottles each of the room has collected. If i type quit at anytime, the program will stop recording bottles and spit out the outcome and the winning room with the most bottles.
How do I get "Enter the room number you are in" to show up first before I enter in the bottle count? My problem exists in getBottles()
I think this line cant be used in an array, am i right?
rooms[room - 1] += int.Parse(Console.ReadLine());
namespace BottleDrive
{
class BottleDrive
{
public int[] rooms;
public BottleDrive()
{
rooms = new int[4];
}
static void Main(string[] args) //static is member of class not object
{
BottleDrive bD = new BottleDrive();
bD.getBottles();
bD.displayBottleCount();
bD.findWinner();
}
public void getBottles()
{
string quit = Console.ReadLine();
while while(quit != "quit")
{
int room = int.Parse(quit);
Console.Write("Bottles collected in room {0}: ", room);
rooms[room - 1] += int.Parse(Console.ReadLine());
Console.Write("Enter the room you're in: ");
}
}
public void findWinner()
{
int maxValue = 0;//initiates the winner, contructor starts at 0
int maxRoomNumber = 0;//initiates the room number that wins
for (int i = 0; i < rooms.Length; ++i)//This loop goes through the array of rooms (4)
{
if (rooms[i] > maxValue)//Makes sure that the maxValue is picked in the array
{//Looking for room number for the
maxValue = rooms[i];
maxRoomNumber = i + 1;
}
}
Console.WriteLine("And the Winner is room " + maxRoomNumber + "!!!");
}
public void displayBottleCount()
{
Console.WriteLine("Bottles collected in room one: " + rooms[0]);
Console.WriteLine("Bottles collected in room two: " + rooms[1]);
Console.WriteLine("Bottles collected in room three: " + rooms[2]);
Console.WriteLine("Bottles collected in room four: " + rooms[3]);
}
}
}
while (quit == "quit")
The above line will only run the loop if quit (what you got from the console) is "quit".
You want:
while (quit != "quit")
or
while (!quit.Equals("quit"))
After all that though you are also not actually updating quit inside your loop so once in you will never get out.
You'll need to capture your console.Readline and put it into "quit".
You probably also want to look at int.TryParse in case people type in a string that isn't quit or a valid integer. TryParse will tell you whether the parse was successful or not rather than throwing an exception.
This line:
while (quit == "quit")
should actually be:
while (quit != "quit")
Or better yet:
while (!quit.Equals("quit", StringComparison.CurrentCultureIgnoreCase))
Which will ignore case for the input. As others have noted, there's more issues with your loop. Try using this for your getBottles function:
public void getBottles()
{
string input;
do
{
Console.Write("Enter the room you're in: (or quit)");
input = Console.ReadLine();
int room;
// doing try parst because the input might be "quit" or other junk
if (int.TryParse(input, out room))
{
Console.Write("Bottles collected in room {0}: ", room);
// this will fail hard if the input is not of type int
rooms[room - 1] += int.Parse(Console.ReadLine());
}
} while (!input.Equals("quit", StringComparison.CurrentCultureIgnoreCase));
}
Should you have while(quit != "quit") for the while condition perhaps?
Try:
while (!quit.Equals("quit"))
The function getBottles() looks very strange. You only enter the while loop when you type "quit". I don't think that this is the behaviour you want.