C# Console Application Dartgame - c#

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);
}
}
}

Related

add sex to passenger on buss program 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!

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);
}
}
}

How to move this code to class/method?

I am doing a web class in programming C#. I want to say right of the bat that I do not want you guys to do my work for me. Now to my specific/generic problem. I am used to writing sequential code. It is when I try to move my working code (s) to classes/methods I get in deep dodo.
The code example below is for a guessing game 1-100. I have tried for four hours straight do break code out in to a separate Class. I manage to get the user input or the RND in to a class. Then the logic in main breaks down. It seems like I get best result if the RND block is Static but user input is not Static etc., etc. In the end I went back to scratch with everything in Main and turn to you for generic guidelines.
I need to get this in my head so I can clean up my Main every time. Start at Class Program Ignore Screen that is working.
<--------Code Below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Uppgift3GissaTalet
{
static class Screen
{
// Screen - Tools that I use every time ignore until end of screen======================================= >
// Methods for screen handling:
//
// Clear Screen ------------------------------------------
static public void cls()
{
Console.Clear();
}
// Set Curser Posittion ----------------------------------
static public void cup(int column, int rad)
{
Console.SetCursorPosition(column, rad);
}
// Key Input --------------------------------------------
static public ConsoleKeyInfo inKey()
{
ConsoleKeyInfo in_key; in_key = Console.ReadKey(); return in_key;
}
// String Input -----------------------------------------
static public string inStr()
{
string in_string; in_string = Console.ReadLine(); return in_string;
}
// Int Input -------------------------------------------
static public int inInt()
{
int int_in; try { int_in = Int32.Parse(Console.ReadLine()); }
catch (FormatException) { Console.WriteLine("Input Error \b"); int_in = 0; }
catch (OverflowException) { Console.WriteLine("Input Owerflow\b"); int_in = 0; }
return int_in;
}
// Float Input -------------------------------------------
static public float inFloat()
{
float float_in; try { float_in = Convert.ToSingle(Console.ReadLine()); }
catch (FormatException) { Console.WriteLine("Input Error \b"); float_in = 0; }
catch (OverflowException) { Console.WriteLine("Input Owerflow\b"); float_in = 0; }
return float_in;
}
// Meny ------------------------------------------------
static public int meny(string rubrik, string m_val1, string m_val2)
{ // Meny med 2 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menSvar = menyInm();
return menSvar;
}
static public int meny(string rubrik, string m_val1, string m_val2, string m_val3)
{ // Meny med 3 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menSvar = menyInm();
return menSvar;
}
static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4)
{ // Meny med 4 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menSvar = menyInm();
return menSvar;
}
static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4, string m_val5)
{ // Meny med 5 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menyRad(m_val5); menSvar = menyInm();
return menSvar;
}
static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4, string m_val5, string m_val6)
{ // Meny med 6 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menyRad(m_val5); ; menyRad(m_val6); menSvar = menyInm();
return menSvar;
}
static void menyRubrik(string rubrik)
{ // Meny rubrik --------
cls(); Console.WriteLine("\n\t {0}\n----------------------------------------------------\n", rubrik);
}
static void menyRad(string menyVal)
{ // Meny rad --------
Console.WriteLine("\t {0}", menyVal);
}
static int menyInm()
{ // Meny inmating ------
int mVal; Console.Write("\n\t Menyval : "); mVal = inInt(); return mVal;
}
// Screen - End <========================================
} // screen <----
class Program
{
static void Main(string[] args)
{//Foreign bla bla.
string rubrik = "\tGissa ett tal mellan 1 och 100: ";
Random rnd = new Random();
int slumpTal = rnd.Next(1, 101);
int svar;
int count = 0;
Screen.cls();
//Console.Write("\t\t" + slumpTal); //Used for fixing logic.
Console.WriteLine("\n\t {0}\n\t----------------------------------------------\n", rubrik);
Console.Write("\tSkriv ditt tal: ");
svar = Screen.inInt();
count++;
//Foreign yadda yadda.
do
{
if (svar < 1 || svar > 100) //Påminn användaren om att hålla sig inom ramarna.
{
System.Console.Write("\tTalet du söker är inom intervallet 1-100!", svar);
Console.Write("\n\tSkriv ditt tal: ");
svar = Screen.inInt();
}
else if (slumpTal > svar && (slumpTal - svar < 6)) //Getting hotter.
{
System.Console.Write("\tTalet du söker är större än {0} men du är nära nu!", svar);
Console.Write("\n\tSkriv ditt tal: ");
svar = Screen.inInt();
count++;
}
else if (slumpTal > svar) //Ge ledtråd om att användaren måste skriva ett större tal.
{
System.Console.Write("\tTalet du söker är större än {0}.", svar);
Console.Write("\n\tSkriv ditt tal: ");
svar = Screen.inInt();
count++;
}
else if (slumpTal < svar && (svar - slumpTal < 6)) //Getting hotter.
{
System.Console.Write("\tTalet du söker är mindre än {0} men du är nära nu!", svar);
Console.Write("\n\tSkriv ditt tal: ");
svar = Screen.inInt();
count++;
}
else if (slumpTal < svar) //Ge ledtråd om att användaren måste skriva ett lägre tal.
{
System.Console.Write("\tTalet du söker är mindre än {0}.", svar);
Console.Write("\n\tSkriv ditt tal: ");
svar = Screen.inInt();
count++;
}
} while (svar != slumpTal);
Screen.cls();
Console.ForegroundColor = ConsoleColor.Green; //Changing colour(sic!) at win.
Console.Write("\n\n\t\tBra jobbat, du löste problemet. Rätt svar är {0}!\n\t\tDu tog {1} försök på dig.", slumpTal, count);
Screen.inKey();
}//<------------Main
}//<===========Program
}
I've just tried to break it up a bit. It's harder to interpret what you are creating without using English naming, however the principles are the same.
Create objects within your main, of the classes you've created.
class Program
{
static void Main(string[] args)
{
string rubrik;
string m_val1;
string m_val2;
Utilities utility = new Utilities();
string str = Console.ReadLine();
int myint = utility.inInt(str);
MyClass myclass = new MyClass();
// or
// getting these values before doing so
MyClass class = new MyClass(rubrik, m_val1, m_val2);
myclass.Method(myint); // etc
The variables that will be passed in may be used in class methods
Or may become initialisers for an instantiation of that class.
public class MyClass
{
// class members
// eg ???
public string Rubrik {get; set;}
// constructors
public MyClass(){}
public MyClass(string rubrik, string m_val1, string m_val2)
{
Rubrik = rubrik;
// and so on.
}
// TODO .. add these menyRad(m_val1);
// menyRad(m_val2); menyRad(m_val3);
// menyRad(m_val4); menSvar = menyInm();
public int meny(string rubrik, string m_val1, string m_val2)
{
int menSvar;
// Use class members to do some calculation and return the value
return menSvar;
}
// etc
}
Create a separate Utilities class for any house keeping methods.
public class Utilities
{
// Int Input -------------------------------------------
public int inInt(string input)
{
int int_in;
try
{
int_in = Int32.Parse(intput);
}
catch (FormatException)
{
Console.WriteLine("Input Error \b");
int_in = 0;
}
catch (OverflowException)
{
Console.WriteLine("Input Owerflow\b");
int_in = 0;
}
return int_in;
}
// Float Input -------------------------------------------
public float inFloat(string input)
{
... etc
}
}

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