add sex to passenger on buss program C# - c#

I just finished a programming 1 class and the last assignment I was making was named "the buss" where I was supposed to identify the different passengers on the buss. Sort the by age, count the average age on the buss and so on. But there were some things I didn't figure out in time and trying to do it now and was looking is someone could help me.
My problem is that I'm supposed to identify their sex and I just can't figure out how to make that.
The second one is to "poke them" and based on different age and sex make different comments.
using System;
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Security.Cryptography;
namespace Bussen
{
class Buss
{
//passagerare means passenger
public int[] passagerare = new int[25];
public int antal_passagerare;
public void Run()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Welcome to the awesome Buss-simulator");
int menu;
do
{
//the menu of every choise you can make.
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Välj ett alternativ: ");
Console.WriteLine("1. Lägg till en passagerare. ");
Console.WriteLine("2. Kontrollera åldern på passagerarna. ");
Console.WriteLine("3. Beräkna den sammanlagda åldern på passagerarna. ");
Console.WriteLine("4. Beräkna medelåldern på passagerarna. ");
Console.WriteLine("5. Identifiera den äldsta passageraren. ");
Console.WriteLine("6. Hitta åldern. ");
Console.WriteLine("7. Sortera bussen efter ålder. ");
Console.WriteLine("8. Print sex. ");
Console.WriteLine("0. Avsluta programmet. ");
menu = int.Parse(Console.ReadLine());
switch (menu)
{
case 1:
add_passenger();
break;
case 2:
Print_buss();
break;
case 3:
Calc_total_age();
break;
case 4:
Calc_average_age();
break;
case 5:
Max_age();
break;
case 6:
Find_age();
break;
case 7:
Sort_buss();
break;
case 8:
Print_sex();
break;
case 0:
menu = 0;
break;
}
} while (menu != 0);
}
//where you add you passengers by age
public void add_passenger()
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Skriv in hur många passagerare ni vill lägga till.");
string str1 = Console.ReadLine();
int size = Convert.ToInt32(str1);
for (int i = 0; i < size; i++)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Lägg till en passagerare genom att skriva in personens ålder ålder: ");
string answer = Console.ReadLine();
int nya_passagerare = Convert.ToInt32(answer);
passagerare[i] = nya_passagerare;
antal_passagerare++;
}
}
// this is where you print out all the passengers.
public void Print_buss()
{
for (int i = 0; i < antal_passagerare; i++)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine("Passagerarnas ålder är: " + passagerare[i]);
}
}
//this is where you add the total age on every passenger.
public void Calc_total_age()
{
int sum = 0;
for (int i = 0; i < passagerare.Length; i++)
{
sum += passagerare[i];
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Den sammanlagda åldern på passagerarna är " + sum + ".");
}
//where you calculate the average age on the buss
public void Calc_average_age()
{
int sum = 0;
for (int i = 0; i < antal_passagerare; i++)
{
sum += passagerare[i];
}
double dsum = Convert.ToDouble(sum);
double dsum1 = dsum / antal_passagerare;
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Passagerarnas medelålder är " + dsum1 + " år.");
Console.WriteLine(" ");
}
//where you find the oldest passenger on the buss
public void Max_age()
{
int maxAge = passagerare[0];
foreach (var enPassagerare in passagerare)
if (enPassagerare > maxAge)
maxAge = enPassagerare;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Den äldsta passageraren är " + maxAge + " år gammal.");
}
//this where you find with seat the diffent passengers sitt on between surtn ages
public void Find_age()
{
bool found = false;
Console.WriteLine("Vilken är den yngst åldern som du vill hitta ?");
int yngst = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Vilken är det högst åldern som du vill hitta ?");
int högst = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Passagerarna som mellan åldern " + yngst + " - " + högst + " sitter i : ");
for (int i = 0; i < passagerare.Length; i++)
{
if (passagerare[i] > högst || passagerare[i] > yngst)
{
Console.WriteLine("stolen " + i);
found = true;
}
}
if(!found)
{
Console.WriteLine("OBS det finns inte sån ålder i bussen ");
}
}
//this is where you sort the buss from ungest to oldest passenger
public void Sort_buss()
{
int temp;
for (int i = 0; i < passagerare.Length - 1; i++)
{
for (int j = 0; j < passagerare.Length - 1 - i; j++)
{
if (passagerare[j] > passagerare[j + 1])
{
temp = passagerare[j];
passagerare[j] = passagerare[j + 1];
passagerare[j + 1] = temp;
}
}
}
for (int i = 0; i < passagerare.Length; i++)
{
Console.WriteLine("Passagerare " + (i + 1) + " är " + passagerare[i] + " år gammal ");
}
}
//this is where im supose to identify with sex every passenger has...
public void Print_sex()
{
for (int k = 0; k < info.Length +1; k++)
{
Console.WriteLine("Plats" + info[k] + kön);
}
}
class Program
{
public static void Main(string[] args)
{
var minbuss = new Buss();
minbuss.Run();
var mysex = new sex();
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.Write("press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
}

Like others have suggested, the best way to do this is to refactor (change) your code to use classes. This is called object oriented programming. I'll try my best to explain it for your current level of experience.
Firstly, create a class. Let's call this "Person".
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Sex { get; set; }
}
Secondly, let's create a list to hold the people on the bus. Instead of creating an array with a set size, we'll create a List.
List<Person> People = new List<Person>();
Now, in your "add_passenger" method, which I advise you rename to follow the general coding standards, to "AddPassenger".
public void AddPassenger()
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Skriv in hur många passagerare ni vill läggatill.");
// Let's presume the input is in the format Name, Age, Sex.
string input = Console.ReadLine();
// This will create a string array with all the "details".
// E.g [0] = Name, [1] = Age, Sex [2].
string[] personDetails = input.Split(",");
// Instantiate a person object and populate the properties.
Person person = new Person();
person.Name = personDetails[0].Trim();
person.Age = Convert.ToInt32(personDetails[1].Trim());
person.Sex = personDetails[2].Trim();
// Add the newly created person to the people list.
People.Add(person);
}
Now you're probably thinking that your bus can a very large amount of people, which is right because a List can hold a couple billion items - that's a pretty big bus! I would advise to add a method that checks the count is less than 25 before the AddPassenger() method call within your switch statement.
I would also like to advise that C# has an incredibly powerful ability to do searches within lists and can even perform mathematical calculations for you in one liners using something called LINQ. An example of this from your sample code would be your "Calc_total_age" method - which I would rename to CalculateTotalAge (it's better to be specific what a function does than to abbreviate. This helps other developers working on your code understand what it's doing if it's clear.
public void CalculateTotalAge()
{
Console.ForegroundColor = ConsoleColor.Red;
// Calculate the total age using a LINQ expression.
int totalAge = People.Sum(x => x.Age);
Console.WriteLine($"Den sammanlagda åldern på passagerarna är {totalAge}");
}
Finally, to answer your question about listing the age of every person on the bus, we can do the following.
public void ListSexOfEveryPerson()
{
foreach(Person person in people)
{
Console.WriteLine($"{person.Name}'s sex is {person.Sex}");
}
}
If we wanted to get creative and use LINQ expressions, we could do:
public void ListSexOfEveryPerson()
{
people.ForEach(p => Console.WriteLine($"{p.Name}'s sex is {p.Sex}"));
}
If LINQ expressions are confusing at this time, then just use the first example until you feel comfortable, there's nothing wrong with a foreach loop!
Also, if you're wondering what the '$' symbol before the quotation is used for, it's for string interpolation. It's a better way of 'injecting' values into a string instead of doing "X" + "X" + "X".
Hope this helps!

Related

unable to print out list objects in different cases in a switch statement

I am making an interface to store character and dinosaur variables to a list and then print them out when asked.
There is a switch statement to take the users' inputs:
Case 1: The function allows the user to input character data and then it's put into a list.
Case 2.: The function allows the user to input dinosaur
data and then it put into a list.
Case 3 The function prints the objects in each list. However, whenever I run it it doesn't print anything and comes up with no errors. If I run the code to print each list in their respective case then they print out fine.
class Program
{
static void Main()
{
int NumAns;
Console.WriteLine("*1. Character Creator ");
Console.WriteLine("*2. Dinosaur Creator ");
Console.WriteLine("*3. Display ");
Console.WriteLine("");
Console.WriteLine("Specify your menu choice");
string NumAnsString = Console.ReadLine();
NumAns = Convert.ToInt32(NumAnsString);
MenuChosen(NumAns);
}
static void MenuChosen(int selection)
{
List<Dinosaur> Dinosaur_l = new List<Dinosaur>();
List<Character> CharSave = new List<Character>();
Character character = new Character();
Dinosaur dinosaur = new Dinosaur();
switch (selection)
{
case 1:
Console.WriteLine("You chose Character Creator");
character.CharacterVal();
CharSave.Add(new Character
{
name = character.name,
age = character.age,
height = character.height,
hair = character.hair,
eyes = character.eyes,
glasses = character.glasses
});
Main();
break;
case 2:
Console.WriteLine("You chose Dinosaurs");
dinosaur.DinoVal();
Dinosaur_l.Add(new Dinosaur
{
name = dinosaur.name,
species = dinosaur.species,
diet = dinosaur.diet,
sex = dinosaur.sex
});
Main();
break;
case 3:
Console.WriteLine(" ");
Console.WriteLine("Character: ");
Console.WriteLine(" ");
foreach (Character chara in CharSave)
{
Console.WriteLine(chara.name);
Console.WriteLine(chara.age);
Console.WriteLine(chara.height);
Console.WriteLine(chara.hair);
Console.WriteLine(chara.eyes);
Console.WriteLine(chara.glasses);
}
Console.WriteLine(" ");
Console.WriteLine("Dinosaurs: ");
Console.WriteLine(" ");
foreach (Dinosaur Dino in Dinosaur_l)
{
Console.WriteLine(Dino.name);
Console.WriteLine(Dino.species);
Console.WriteLine(Dino.diet);
Console.WriteLine(Dino.sex);
}
Console.WriteLine(" ");
Main();
break;
}
}
}
This is the code used for CharacterVal function
public class Character
{
public string name;
public string age;
public string height;
public string hair;
public string eyes;
public string glasses;
public int charID = 0;
int x = 1;
public void CharacterVal()
{
charID++;
Console.WriteLine("Name your Character: ");
name = Console.ReadLine();
Console.WriteLine("How old is " + name + "? :");
age = Console.ReadLine();
Console.WriteLine("How tall is " + name + "?: ");
height = Console.ReadLine();
Console.WriteLine("What colour is " + name + "'s hair ?: ");
hair = Console.ReadLine();
Console.WriteLine("What colour is " + name + "'s eyes ?: ");
eyes = Console.ReadLine();
GlassesCheck();
}
public void GlassesCheck()
{
Console.WriteLine("does " + name + " wear glasses? (yes/no): ");
while (x == 1)
{
glasses = Console.ReadLine();
if(glasses =="yes")
{
x = 2;
}
else if(glasses == "no")
{
x = 2;
}
else
{
x = 1;
Console.WriteLine("'"+glasses+"' is not a valid answer, does " + name + " wear glasses? (yes/no): ");
}
}
}
}
This is the code used for the DinoVal function
public class Dinosaur
{
public string species;
public string diet;
public string sex;
public string name;
public void DinoVal()
{
Console.WriteLine("***************************");
Console.WriteLine("*Choose a Dinosaur *");
Console.WriteLine("* *");
Console.WriteLine("*1. Alvarezsaurus *");
Console.WriteLine("*2. Avimimus *");
Console.WriteLine("*3. Bactrosaurus *");
Console.WriteLine("*4. Baryonyx *");
Console.WriteLine("*5. Coloradisaurus *");
Console.WriteLine("*6. Chungkingosaurus *");
Console.WriteLine("***************************");
int Selection = Convert.ToInt32(Console.ReadLine());
switch (Selection)
{
case 1:
Console.WriteLine("you have chosen the Alvarezsaurus");
Console.WriteLine("This is a Carnivore ");
species = "Alvarezsaurus";
diet = "Carnivore";
break;
case 2:
Console.WriteLine("you have chosen the Avimimus");
Console.WriteLine("This is an Omnivore ");
species = "Avimimus";
diet = "Omnivore";
break;
case 3:
Console.WriteLine("you have chosen the Bactrosaurus");
Console.WriteLine("This is a Herbivore ");
species = "Bactrosaurus";
diet = "Herbivore";
break;
case 4:
Console.WriteLine("you have chosen the Baryonyx");
Console.WriteLine("This is a Carnivore ");
species = "Baryonyx";
diet = "Carnivore";
break;
case 5:
Console.WriteLine("you have chosen the Coloradisaurus");
Console.WriteLine("This is an Omnivore ");
species = "Coloradisaurus";
diet = "Omnivore";
break;
case 6:
Console.WriteLine("you have chosen the Chungkingosaurus");
Console.WriteLine("This is a Herbivore ");
species = "Chungkingosaurus";
diet = "Herbivore";
break;
}
Console.WriteLine("Please choose the dinosaurs sex");
Console.WriteLine("1.Male");
Console.WriteLine("2.Female");
int GenderChoice = Convert.ToInt32(Console.ReadLine());
switch (GenderChoice)
{
case 1:
Console.WriteLine("the dinosaur will be male");
sex = "Male";
break;
case 2:
Console.WriteLine("the dinosaur will be female");
sex = "Female";
break;
}
Console.WriteLine("What name will you give this " + sex + " " + species + " ?:");
name = Console.ReadLine();
}
}
i've tried moving
CharSave.Add(new Character
{
name = character.name,
age = character.age,
height = character.height,
hair = character.hair,
eyes = character.eyes,
glasses = character.glasses
});
into case 3 but all that does is print blank spaces for each object
The lists that store the characters and the dinos need to be outside of the MenuChosen method because as you code is written everytime MenuChosen is called new lists are created.
You could:
class Program
{
static List<Dinosaur> Dinosaur_l = new List<Dinosaur>();
static List<Character> CharSave = new List<Character>();
}
Main -> MenuChosen -> Main -> MenuChosen -> ...
Because the way you structured (Main calls MenuChosen which calls Main and so on) your code - if you run the game for long enough - will get end up with a stack overflow.
To avoid this you can run your code in a loop:
Main()
{
while (true) // or selection was 'Quit', etc.
{
your code here
}
// Remove calls to 'Main' from the switch statement.

Save user input from a switch-case that is stored in a list (beginner) C#

For each switch loop that is performed, all information that the user has entered is deleted.
The user provides information via case 1 which has the methods: läsPoäng (readPoints) and omvandlaBetyg (convertRate).
How can I proceed to make the loop remember the user's input?
I have different lists that consist of different variables used for my methods.
Comments have been added to give a better explanation.
I appreciate all help I can get.
static void Main(string[] args)
{
List<string> ämnen = new List<string> { "Matematik", "Svenska", "Engelska", "Historia", "Fysik" };
List<int> poäng = new List<int>(); // Declaration of list with points
List<char> betyg = new List<char>(); // Declaration of list with grades
bool repetera = true;
do
{
Console.WriteLine(" \n========Räkna betyg========");
Console.WriteLine("1. Skriv in dina poäng");
Console.WriteLine("2. Skriv ut dina betyg");
Console.WriteLine("3. Poäng & betyg statistik");
Console.WriteLine("4. Avsluta");
Console.WriteLine("==========================");
Console.Write("Ange ditt alternativ: ");
int alternativ = Convert.ToInt32(Console.ReadLine());
switch (alternativ)
{
// I want to be able to save the input from the user in case 1
// so that it can be used in other cases.
case 1:
läsPoäng(ämnen); // Method that asks for the user to input points for specific courses
omvandlaBetyg(poäng); // Method that converts user input to char "grades"
Console.Clear();
break;
case 2:
skrivUtBetyg(betyg, ämnen); // Method that show grades for each course
break;
case 3:
Statistik(betyg, poäng); // Method that show statistics for the points and grades
break;
case 4:
Console.WriteLine("Tack för att du använt programmet 'Räkna betyg'");
repetera = false;
break;
default:
Console.WriteLine("\nVänligen ange ett alternativ mellan 1-4.\n");
break;
}
}
while (true);
}
// Method that asks for the user to input points for specific courses
static List<int> läsPoäng(List<string> ämnen)
{
var poäng = new List<int>();
Console.Write("Ange totalpoäng för matematik:");
poäng.Add(Convert.ToInt32(Console.ReadLine()));
Console.Write("Ange totalpoäng för svenska:");
poäng.Add(Convert.ToInt32(Console.ReadLine()));
Console.Write("Ange totalpoäng för engelska:");
poäng.Add(Convert.ToInt32(Console.ReadLine()));
Console.Write("Ange totalpoäng för historia:");
poäng.Add(Convert.ToInt32(Console.ReadLine()));
Console.Write("Ange totalpoäng för fysik:");
poäng.Add(Convert.ToInt32(Console.ReadLine()));
return poäng;
}
// Method that converts user input to char "grades"
static List<char> omvandlaBetyg(List<int> poäng)
{
List<char> betyg = new List<char>();
foreach (int i in poäng)
{
if (i < 50)
{
betyg.Add('F');
}
else if (i <= 60)
{
betyg.Add('E');
}
else if (i < 75)
{
betyg.Add('D');
}
else if (i < 90)
{
betyg.Add('C');
}
else if (i < 100)
{
betyg.Add('B');
}
else
{
betyg.Add('A');
}
}
return betyg;
}
// Method that show grades for each course
static void skrivUtBetyg(List<char> betyg, List<string> ämnen)
{
// Använder mig utav metoden .Zip för att slå ihop betyget med
// sitt motsvarande ämne. För att sedan kunna presentera allt
// i samma linje som visar betyget och ämnet "zippat" till en linje.
// (Utan denna .Zip lösning så hade man fått göra två separate foreach-loopar
// som då visar ämnena och betygen separat.
// Denna lösning fungerar utmärkt för att iterera igenom två listor samtidigt.
var betygOchÄmnen = betyg.Zip(ämnen, (first, second) => first + " |" + second);
Console.WriteLine(" \n_________________________");
Console.WriteLine("| Betyg | Ämne ");
foreach (var item in betygOchÄmnen)
{
Console.WriteLine("| " + item);
}
Console.WriteLine("_________________________");
}
// Method for showing grade and points statistics
static void Statistik(List<char> betyg, List<int> poäng)
{
int betygA = 0;
int betygC = 0;
int betygF = 0;
int totalPoäng = poäng.Sum();
foreach (var c in betyg)
{
if (c == 'A')
{
betygA++;
}
else if (c == 'C')
{
betygC++;
}
else if (c == 'F')
{
betygF++;
}
}
Console.WriteLine(" \n========================");
Console.WriteLine("|Antal A betyg: " + betygA + " |");
Console.WriteLine("|Antal C betyg: " + betygC + " |");
Console.WriteLine("|Antal F betyg: " + betygF + " |");
Console.WriteLine("|Antal betygspoäng: " + totalPoäng + "|");
Console.WriteLine("========================");
}
}
}
The solution has been found.
I had to add a list for the input to be stored into.
As you can see below:
poäng = läsPoäng(ämnen);
betyg = omvandlaBetyg(poäng);

Card game incrementing in a do while(c#)

I've been stuck at this exercise of making an array of cards and then picking a random card out of the first array and then storing it in the second one. My choice of loop is a do while where I increment I (the position of the card in the second array). Although it seems that i does not increment as i thought it would. Could somebody please tell me where i went wrong with this exercise it should be a really easy solve. Thanks in advance.
static void Main(string[] args)
{
string[] myCards = new string [52] {"H1","H2","H3","H4","H5","H6","H7","H8","H9","HT","HJ","HQ","HK",
"D1", "D2","D3","D4","D5","D6","D7","D8","D9","DT","DJ","DQ","DK",
"C1", "C2","C3","C4","C5","C6","C7","C8","C9","CT","CJ","CQ","CK",
"S1", "S2","S3","S4","S5","S6","S7","S8","S9","ST","SJ","SQ","SK"};
int i=0;
bool stopPlaying= true;
string[] arrDeckOfCardsPulled;
arrDeckOfCardsPulled = new string[i+1];
do
{
Console.Write("Choose one of the following options:");
Console.WriteLine("\t'A' : To pick a card.");
Console.WriteLine("\t\t\t\t\t"+"'B' : To fold the deck and END the game.");
string playOrNot = Console.ReadLine();
Random random = new Random();
int randomCard = random.Next(0,52);
string valueOfMycard = myCards[randomCard];
if (randomCard != Array.IndexOf(arrDeckOfCardsPulled, randomCard)) {
switch (playOrNot)
{
case "A":
{
arrDeckOfCardsPulled[i] = valueOfMycard;
Console.WriteLine();
Console.WriteLine("This is the card you picked: " + myCards[randomCard]);
Console.WriteLine();
Console.WriteLine("This is the position of your card in the first array: " + Array.IndexOf(myCards, valueOfMycard));
Console.WriteLine();
Console.WriteLine("This is the position of your card in the second array: " + Array.IndexOf(arrDeckOfCardsPulled, valueOfMycard));
i ++;
}
break;
case "B":
Console.WriteLine();
Console.Write("These are the cards that you pulled:");
foreach (string card in arrDeckOfCardsPulled)
{
Console.Write(card+" ");
}
Console.WriteLine();
Console.Write("I am folding the deck.");
Console.WriteLine();
Console.Write("\n\t\t\t\t\t\t THE END");
Console.WriteLine("\n");
Console.ReadKey();
stopPlaying = false;
break;
default:
break;
}
Console.WriteLine("\n");
}
} while (stopPlaying||(i)<52);
}
I was foolish
An array size is fixed as soon as it is initialized. I'm a total beginner forgive me for wasting your time this is my solution.
static void Main(string[] args)
{
string[] myCards = new string [52] {"H1","H2","H3","H4","H5","H6","H7","H8","H9","HT","HJ","HQ","HK",
"D1", "D2","D3","D4","D5","D6","D7","D8","D9","DT","DJ","DQ","DK",
"C1", "C2","C3","C4","C5","C6","C7","C8","C9","CT","CJ","CQ","CK",
"S1", "S2","S3","S4","S5","S6","S7","S8","S9","ST","SJ","SQ","SK"};
int arrayposition = 0;
bool stopPlaying= true;
string[] arrDeckOfCardsPulled;
arrDeckOfCardsPulled = new string[52];
do
{
Console.Write("Choose one of the following options:");
Console.WriteLine("\t'A' : To pick a card.");
Console.WriteLine("\t\t\t\t\t"+"'B' : To fold the deck and END the game.");
string playOrNot = Console.ReadLine();
Random random = new Random();
int randomCard = random.Next(0,52);
string valueOfMycard = myCards[randomCard];
if (randomCard != Array.IndexOf(arrDeckOfCardsPulled, valueOfMycard)) {
switch (playOrNot)
{
case "A":
{
arrDeckOfCardsPulled[arrayposition] = valueOfMycard;
Console.WriteLine();
Console.WriteLine("This is the card you picked: " + myCards[randomCard]);
Console.WriteLine();
Console.WriteLine("This is the position of your card in the first array: " + Array.IndexOf(myCards, valueOfMycard));
Console.WriteLine();
Console.WriteLine("This is the position of your card in the second array: " + Array.IndexOf(arrDeckOfCardsPulled, valueOfMycard));
arrayposition++;
}
break;
case "B":
string[]yourpulls=new string[arrayposition+1];
Array.Copy(arrDeckOfCardsPulled, 0, yourpulls,0, arrayposition);
Console.WriteLine();
Console.Write("These are the cards that you pulled: ");
foreach (string card in yourpulls)
{
Console.Write(card+" ");
}
Console.WriteLine();
Console.Write("I am folding the deck.");
Console.WriteLine();
Console.Write("\n\t\t\t\t\t\t THE END");
Console.WriteLine("\n");
Console.ReadKey();
stopPlaying = false;
break;
default:
break;
}
Console.WriteLine("\n");
}
} while (stopPlaying||(arrayposition)<53);
}
}
}

C# Console Application Dartgame

So I'm trying to create a dartgame in Console Application with C#.
This is as far as I have gotten atm:
class Program
{
static void Main(string[] args)
{
Game gameOn = new Game();
gameOn.PlayGame();
}
class Game
{
private List<Players> playerList = new List<Players>();
public void AddPlayers(string name)
{
Players names = new Players(name);
playerList.Add(names);
}
public void PlayGame()
{
Console.WriteLine("Välkommen till Dartspelet! Tryck valfri knapp för att fortsätta...");
Console.ReadLine();
Console.WriteLine("Skriv in antal spelare. Ni kommer också att möta en Dator.");
Console.WriteLine();
int players = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < players; i++)
{
Console.Write("Skriv in spelarens namn: ");
string playersNames = Console.ReadLine();
AddPlayers(playersNames);
}
Console.WriteLine();
Console.WriteLine("Spelet har börjat!");
Console.WriteLine();
foreach (Players name in playerList)
{
Console.WriteLine("Datorn börjar att kasta... Var god vänta...");
System.Threading.Thread.Sleep(2000);
Random rng = new Random();
int ranAttempt1 = rng.Next(0, 21);
int ranAttempt2 = rng.Next(0, 21);
int ranAttempt3 = rng.Next(0, 21);
Attempts result = new Attempts(ranAttempt1, ranAttempt2, ranAttempt3);
Console.WriteLine("Datorn Fick " + result.GetScore() + " på 3 kast.");
Console.ReadLine();
Console.WriteLine(name + "s Tur! ");
Console.WriteLine("Skriv in Poäng mellan 0-20 för kast 1:");
int attempt1 = Int32.Parse(Console.ReadLine());
Console.WriteLine("Skriv in Poäng mellan 0-20 för kast 2:");
int attempt2 = Int32.Parse(Console.ReadLine());
Console.WriteLine("Skriv in Poäng mellan 0-20 för kast 3:");
int attempt3 = Int32.Parse(Console.ReadLine());
Attempts result1 = new Attempts(attempt1, attempt2, attempt3);
Console.WriteLine(name + " Fick " + result1.GetScore());
}
Console.ReadLine();
}
}
class Attempts
{
private int attempt1;
private int attempt2;
private int attempt3;
public Attempts(int attempt1 = 0, int attempt2 = 0, int attempt3 = 0)
{
this.attempt1 = attempt1;
this.attempt2 = attempt2;
this.attempt3 = attempt3;
}
public int GetScore()
{
return attempt1 + attempt2 + attempt3;
}
}
class Players
{
private string Name { get; set; }
public List<Attempts> attempts = new List<Attempts>();
public Players(string name = "")
{
Name = name;
}
public override string ToString()
{
return Name;
}
}
}
I need help with creating a while loop around the foreach loop that will end when one of the players has reached a score of 301 or over. I also need a method to keep the score in a List or something like that for every turn. But yeah I'm stuck so any help is greatly appriciated! :)
And sorry if the code is a bit messy
Thanks in advance!
Well, you already have the List for the player's attempts. You could:
add a while loop around the foreach(Players...):
append the attempt after it's finished.
after a each player's attempts, calculate the total score.
print the score and exit if the total score > 301
while(true)
{
foreach(Players name in playerList)
{
// existing code here
// you should encapsulate attempts with getter and setter,
// but according to your Players class this will work.
name.attempts.add(result1);
// now sum up the total results for the player
// exercise for the reader.
int totalResults = player.getTotalScore();
if(totalResults > 301)
{
Console.WriteLine("Player " + name.getName() + " won the game!");
Environment.exit(0);
}
}
}

Over writing an array and placing a zero back in its place

I'm doing some school work and would just like to be pointed in the right direction. I am creating a Hotel project which books people in and also books them out when leaving. I'm struggling on a certain part which asks which room you need vacating and then puts a 0 into this position in the array. I am not going to beat around the bush i don't know where to start. This is my code so far.
using System;
namespace Task7_2
{
class Motel
{
int[] rooms;
const int MAX = 21;
int roomNumber, guests, vacate;
static void Main()
{
Motel BatesMotel = new Motel();
BatesMotel.runMotel();
BatesMotel.showAllRooms();
}
//*******************************************************
public Motel()
{
rooms = new int[MAX + 1]; // allow rooms from 1 to MAX
}
//******************************************************
public void runMotel()
{
string choice = "";
do
{
Console.Clear();
Console.WriteLine("The Bates Motel");
Console.WriteLine("===============");
Console.WriteLine("1. Book a room");
Console.WriteLine("2. Vacate a room");
Console.WriteLine("3. Display ALL Room Details");
Console.WriteLine("4. Vacate ALL rooms");
Console.WriteLine("5. Quit");
Console.Write("Enter your choice : ");
choice = Console.ReadLine();
if (choice == "1")
{
bookRoom();
}
else if (choice == "3")
{
showAllRooms();
}
else if (choice == "2")
{
vacateOneRoom();
}
}
while (choice != "5");
}
//*******************************************************
public void bookRoom()
{
Console.WriteLine("\nThe Bates Motel");
Console.WriteLine("===============");
Console.WriteLine("Book a room");
Console.Write("Enter the room number : ");
roomNumber = Convert.ToInt32(Console.ReadLine());
Console.Write("How many guests : ");
guests = Convert.ToInt32(Console.ReadLine());
rooms[roomNumber] = guests; // make the booking
Console.WriteLine("Room " + roomNumber + " booked for " + guests + " people");
}
//*******************************************************
public void showAllRooms()
{
for (int i = 1; i < MAX; i++)
{
Console.Write("Room " + (i )+"\t\t\t" + rooms[i] + " guests \n" );
}
Console.ReadLine();
}
public void vacateOneRoom()
{
Console.WriteLine("Which room is being vacated");
Console.ReadLine();
}
}
}
using System.Collections.Generic;
List<int> myList= new List<int>();
int num = 22;
myList.Add(num);
myList.Remove(num); //removes matching item
myList.Add(33);
myList.RemoveAt(0); //removes at array index
bool[] barray = new bool[number_of_rooms];
When someone booked a particular room then
barray[room_number]=true;
When someone vacate a particular room then
barray[room_number]=false;
checking
for(int i=0;i<barray.lenght;i++)
{
if(barray[i]==true)
Console.WriteLine("Room number"+300+i+"is not free");
else
Console.WriteLine("Room number"+300+i+"is free");
}
example output:::
Room number 300 is not free
Room number 301 is not free
Room number 302 is free
Room number 303 is not free
Room number 304 is free

Categories

Resources