C# Simulation Closing - c#

I just finished my little 2 Person game, but as soon as i finish to enter the 2 colours it just closes on the next Key pressed. I don't find an error, maybe someone can help me? Or also just tell me how to improve my code. I only recently started programming with C# and am thankful for help
My Programm Code is this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fahrrad
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Geben sie die Farbe 'blau' oder 'gruen' ein: ");
Velo Velo1 = new Velo(Console.ReadLine());
Console.WriteLine("Geben sie die andere Farbe ein: ");
Velo Velo2 = new Velo(Console.ReadLine());
ConsoleKeyInfo input;
input = Console.ReadKey();
switch(input.Key)
{
case ConsoleKey.UpArrow:
Velo2.Gangwechsel(1);
break;
case ConsoleKey.DownArrow:
Velo2.Gangwechsel(0);
break;
case ConsoleKey.LeftArrow:
Velo2.Bremse(true);
break;
case ConsoleKey.RightArrow:
Velo2.Fortbewegung(true);
break;
case ConsoleKey.W:
Velo1.Gangwechsel(1);
break;
case ConsoleKey.S:
Velo1.Gangwechsel(0);
break;
case ConsoleKey.A:
Velo1.Bremse(true);
break;
case ConsoleKey.D:
Velo1.Fortbewegung(true);
break;
}
}
}
}
And my Class Code is this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Fahrrad
{
internal class Velo
{
private double gaenge;
private bool bremse;
private string farbe;
private double maxGang;
private bool fahrend;
// Konstruktor
public Velo(string farbe)
{
this.gaenge = 1;
this.farbe = farbe;
if(farbe == "blau")
{
maxGang = 7;
}
else if (farbe == "gruen")
{
maxGang = 3;
}
else
{
Console.WriteLine("Falsche eingabe");
Console.ReadKey();
System.Environment.Exit(1);
}
}
public void Gangwechsel(double schalten)
{
if(schalten == 0)
{
this.gaenge--;
if(this.gaenge == 0 && this.fahrend == true)
{
this.gaenge = 1;
Console.WriteLine("Sie sind bereits im tiefsten gang");
}
}
else if(schalten == 1 && this.fahrend == true)
{
this.gaenge++;
if(this.gaenge > this.maxGang)
{
this.gaenge = this.maxGang;
Console.WriteLine("Sie sind bereits im höchsten Gang");
}
}
else
{
Console.WriteLine("Sie müssen zum Gang wechseln fahren");
}
Console.WriteLine("Sie sind momentan im " + this.gaenge + " gang");
}
public void Bremse(bool bremse)
{
this.bremse = bremse;
if(fahrend == true && this.bremse == true)
{
fahrend= false;
Console.WriteLine("Sie haben die Fahrt beendet");
}
}
public void Fortbewegung(bool fahrend)
{
this.fahrend = fahrend;
if(this.bremse == true && this.fahrend == true)
{
Console.WriteLine("Sie haben die Bremse noch angezogen");
this.fahrend = false;
}
else
{
this.fahrend = true;
Console.WriteLine("Das " + this.farbe + "Fahrrad ist im" + this.gaenge + " Gang losgefahren");
}
}
}
}

You need a game loop that can be terminated by a key.
For example:
static void Main(string[] args)
{
Console.WriteLine("Geben sie die Farbe 'blau' oder 'gruen' ein: ");
Velo Velo1 = new Velo(Console.ReadLine());
Console.WriteLine("Geben sie die andere Farbe ein: ");
Velo Velo2 = new Velo(Console.ReadLine());
ConsoleKeyInfo input;
bool gameIsRunning = true;
while(gameIsRunning)
{
input = Console.ReadKey();
switch(input.Key)
{
// your other rules here
case ConsoleKey.Q:
gameIsRunning = false;
break;
}
}
}

Related

Esc input cuts of Writeline

So I tried to code an userinput with ConsoleKeyInfo. Its works. Than I tried to implement an cancellation when Esc is pressed. It works aswell but it cuts off some of my Writeline. When I try the same code with checking for example M it works just fine!
Is someone able to help?
My Code:
class Program
{
static void Main()
{
while (true)
{
string eingabeArtikelnummer, eingabePlatzalter;
Console.Clear();
Console.Write("Ein neuer Artikel wird angelegt:\n\nGeben Sie die Artikelnummer an: ");
eingabePlatzalter = SteuerungUndEingabe();
if (eingabePlatzalter == ConsoleKey.Escape.ToString()) { break; }
else { eingabeArtikelnummer = eingabePlatzalter; }
}
WartenAufUser();
}
static string SteuerungUndEingabe()
{
ConsoleKey input;
string userEingabe = null;
do
{
input = Console.ReadKey().Key;
if (input == ConsoleKey.Escape)
{
userEingabe = input.ToString();
break;
}
userEingabe += input.ToString();
} while (input != ConsoleKey.Enter);
return (userEingabe);
}
static void WartenAufUser()
{
Console.WriteLine("----------------------------------------------------------------------------------------\n\nBeliebige Taste druecken um ins Menue zu gelangen!");
while (Console.ReadKey() == null) { };
}
}
}
This is the output in the Console:
This is how it should be:
Edit:
So I asked my Teacher how to fix this Problem. He had no idea why it occurs but he recommanded me to go around the Problem and change my Writeline to
Console.WriteLine("x\n----------------------------------------------------------------------------------------\n\nBeliebige Taste druecken um ins Menue zu gelangen!");
The "x\n" miraculously avoids the problem :D

C# How can i use parameter function in my hangman game

I have been asked by my teacher to store my functions inside a parameter driven function and replacing the switch with an if statement. I have no idea how i am supposed to do this. Any help is appreciated.
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace ConsoleApplication6
{
class Hangman
{
public static int lives = 5;
static string[] wordBank = { "study", "cat", "dress", "shoes", "lipstick" };
static ArrayList wordList = new ArrayList(wordBank);
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Title = "C# Hangman";
Console.WriteLine("Hang man!");
string response = "";
do
{
Console.Write("Enter Command (1. Add Words, 2. List Words , 3. Play , 4. Exit) Pick 1-4: ");
response = Console.ReadLine();
switch (response)
{
case "1":
AddWord();
break;
case "2":
ListWords();
break;
case "3":
Play();
break;
case "4":
break;
}
} while (response != "4");
}
static void AddWord()
{
Console.Write("Enter the word to add: ");
String temp = Console.ReadLine();
wordList.Add(temp);
Console.WriteLine("{0} was added to the dictionary!", temp);
}
static void ListWords()
{
foreach (Object obj in wordList)
Console.WriteLine("{0}", obj);
Console.WriteLine();
}
static void AskLives()
{
try
{
Console.WriteLine("please enter number of lives?");
lives = int.Parse(Console.ReadLine());
}
catch
{
AskLives();
}
}
static void Play()
{
Random random = new Random((int)DateTime.Now.Ticks);
string wordToGuess = wordList[random.Next(0, wordList.Count)].ToString();
string wordToGuessUppercase = wordToGuess.ToUpper();
StringBuilder displayToPlayer = new StringBuilder(wordToGuess.Length);
for (int i = 0; i < wordToGuess.Length; i++)
displayToPlayer.Append('-');
List<char> correctGuesses = new List<char>();
List<char> incorrectGuesses = new List<char>();
bool won = false;
int lettersRevealed = 0;
string input;
char guess;
AskLives();
while (!won && lives > 0)
{
Console.WriteLine("Current word: " + displayToPlayer);
Console.Write("Guess a letter: ");
input = Console.ReadLine().ToUpper();
guess = input[0];
if (correctGuesses.Contains(guess))
{
Console.WriteLine("You've already tried '{0}', and it was correct!", guess);
continue;
}
else if (incorrectGuesses.Contains(guess))
{
Console.WriteLine("You've already tried '{0}', and it was wrong!", guess);
continue;
}
if (wordToGuessUppercase.Contains(guess))
{
correctGuesses.Add(guess);
for (int i = 0; i < wordToGuess.Length; i++)
{
if (wordToGuessUppercase[i] == guess)
{
displayToPlayer[i] = wordToGuess[i];
lettersRevealed++;
}
}
if (lettersRevealed == wordToGuess.Length)
won = true;
}
else
{
incorrectGuesses.Add(guess);
Console.WriteLine("Nope, there's no '{0}' in it!", guess);
lives--;
}
Console.WriteLine(displayToPlayer.ToString());
}
if (won)
Console.WriteLine("You won!");
else
Console.WriteLine("You lost! It was '{0}'", wordToGuess);
Console.Write("Press ENTER to exit...");
Console.ReadLine();
}
}
}
Highlight the switch block and select "Quick Actions."
Rename the function after applying the change.

How to handle DivideByZeroExeption

I'm programming a Consolecalculator in C#. My problem is that I don't know how to handle the DivideByZeroExeption in the correct way. I want the user to have the chance to change the the incorrect "0" into another number. That should happen in the same calculation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gmaare_consolen_rechner_1._0
{
class Program
{
//Program Start
public static void Main(string[] args)
{
//jaNein String um zu ermitteln ob erneut eine Rechnung gestellt werden soll
//Der Operator wird in den rechenzeichen String eingelesen
string jaNein, rechenzeichen = (null);
//Start der Rechnerschleife
do {
int zahl_1 = Convert.ToInt32(null); //erste Zahl einlesen
zahl_1 = (Fehlerklasse.fehlerzahl_1(zahl_1)); //erste Zahl weitergeben
rechenzeichen = (Fehlerklasse.fehlerRechenzeichen(rechenzeichen)); //rechenzeichen einlesen
int zahl_2 = Convert.ToInt32(null); //zeite Zahl einlesen
zahl_2 = (Fehlerklasse.fehlerzahl_2(zahl_2)); //zweite Zahl weitergeben
var ergebnis = Ergebnis.rechenmethode(zahl_1, zahl_2, rechenzeichen);
Console.WriteLine(ergebnis); //ergebnis wird ausgelesen
Console.WriteLine("Möchten sie erneut eine Rechnung stellen ? (ja / nein)"); //Frage an den Benutzer
//Start einer schleife zur Ermittlung von jaNein
do
{
jaNein = Console.ReadLine();
if (!(jaNein == "ja" | jaNein == "nein"))
{
Console.WriteLine("Ungültige Antwort, bitte wählen sie (ja / nein)");
}
}
while (!(jaNein == "ja" | jaNein == "nein")); //löscht alles geschriebene in der Konsole
Console.Clear();
}
while (jaNein == "ja"); //Führe die Rechnerschleife aus, solange jaNein "ja" ist
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gmaare_consolen_rechner_1._0
{
class Rechner
{
//Implementieren der Klasse Fehlerklasse
Fehlerklasse fehlerbehen = new Fehlerklasse();
//Methode zum Plusrechnen
public int plus(int zahl_1, int zahl_2)
{
return zahl_1 + zahl_2;
}
//Methode zum Minusrechnen
public int minus(int zahl_1, int zahl_2)
{
return zahl_1 - zahl_2;
}
//Methode zum Malrechnen
public int mal(int zahl_1, int zahl_2)
{
return zahl_1 * zahl_2;
}
//Methode zum Geteiltrechnen
public int geteiltdurch(int zahl_1, int zahl_2)
{
if(zahl_2!= 0)
{
return zahl_1 / zahl_2;
}
else
{
Console.WriteLine("Die Division durch 0 ist verboten!");
return zahl_2;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gmaare_consolen_rechner_1._0
{
class Ergebnis
{
//Methode zur Ermittlung des Operators
public static int rechenmethode(int zahl_1, int zahl_2, string rechenzeichen)
{
//var ergebnis auf 0 gesetzt
var ergebnis = 0;
//Klassen rechnen und Fehlerklasse implementiert
Rechner rechnen = new Rechner();
Fehlerklasse fehlerbehen = new Fehlerklasse();
//Switchanweisung zur Ermittlung des Operators
switch (rechenzeichen)
{
case "+":
ergebnis = rechnen.plus(zahl_1, zahl_2);
break;
case "-":
ergebnis = rechnen.minus(zahl_1, zahl_2);
break;
case "*":
ergebnis = rechnen.mal(zahl_1, zahl_2);
break;
case "/":
ergebnis = rechnen.geteiltdurch(zahl_1, zahl_2);
break;
}
//Gibt die Variable ergebnis zurück
return ergebnis;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gmaare_consolen_rechner_1._0
{
class Fehlerklasse
{
//Methdoe zum Sicherstellen dass zahl_1 eine Zahl ist
public static int fehlerzahl_1(int zahl_1)
{
bool tryAgain = true;
while (tryAgain)
{
try
{
zahl_1 = Convert.ToInt32(Console.ReadLine());
tryAgain = false;
}
catch (FormatException)
{
Console.WriteLine("Geben sie eine gültige Zahl ein!");
}
catch (OverflowException)
{
Console.WriteLine("Die Zahl ist zu gross, geben sie eine gültige Zahl ein!");
}
}
return zahl_1;
}
//Methdoe zum Sicherstellen dass zahl_2 eine Zahl ist
public static int fehlerzahl_2(int zahl_2)
{
bool tryAgain = true;
while (tryAgain)
{
try
{
zahl_2 = Convert.ToInt32(Console.ReadLine());
tryAgain = false;
}
catch (FormatException)
{
Console.WriteLine("Geben sie eine gültige Zahl ein!");
}
catch (Exception )
{
Console.WriteLine("Die Zahl ist zu gross, geben sie eine gültige Zahl ein!");
}
}
return zahl_2;
}
//Methode um zu verhindern dass andere Zeichen als +,-,*,/ als Operator verwendet werden
public static string fehlerRechenzeichen (string rechenzeichen)
{
bool tryAgain = true;
while (tryAgain)
{
try
{
rechenzeichen = Console.ReadLine();
switch (rechenzeichen)
{
case "+":
break;
case "-":
break;
case "*":
break;
case "/":
break;
default:
throw new FormatException();
}
tryAgain = false;
}
catch (FormatException)
{
Console.WriteLine("Geben sie ein gültiges Rechenzeichen ein! (+,-,*,/)");
}
}
return rechenzeichen;
}
}
}
If I understand what you're asking correctly, you simply want to prevent the case where the divisor in the division operation is 0 and prompt the user for a new divisor in that case. This could be handled with a check at the time of the initial input, or you could adjust your division method like this:
//Methode zum Geteiltrechnen
public int geteiltdurch(int zahl_1, int zahl_2)
{
if(zahl_2!= 0)
{
return zahl_1 / zahl_2;
}
else
{
Console.WriteLine("Die Division durch 0 ist verboten!");
Console.Write("Please enter another divisor: ");
zahl_2 = Convert.ToInt32(Console.ReadLine());
//You'll want to do some validation here.
return geteiltdurch(zahl_1, zahl_2);
}
}
You could also do something similar with a while loop. Ultimately, it would be better to check for the 0 before calling the division, though -- that way you don't need to duplicate the checks for whether the input is a number, etc. The basic logic is the same -- write the prompt and read the input until you get a valid nonzero input.
Where you retrieve "rechenzeichen" and "zahl_2" simply have a do while around this part of the code so that you can check that the second number will be compatible with the operator.
var avoidedDivideByZero = false;
do
{
int zahl_2 = Convert.ToInt32(null);
zahl_2 = (Fehlerklasse.fehlerzahl_2(zahl_2));
if(rechenzeichen != #"/" || zahl_2 != 0)
{
avoidedDivideByZero = true;
}
else
{
Console.WriteLine(#"Cannot divide by 0, please enter another number.");
}
}
while(!avoidedDivideByZero)
I think I've understood what "zahl_2" and "rechenzeichen" means. I would refactor this into a separate method so that it does not clutter your main loop with checks but should allow you to continue just now.

How do I jump into another menu without nesting unnecessarily?

I'm stuck with the following code and what I'm trying to achieve now, is to NOT nest switches/if statements any further, which would result in ugly code, I assume. To visualize my intention:
ConsoleKeyInfo keyE = Console.ReadKey();
if (keyE.Key == ConsoleKey.Enter && iMOP == 1){
//Jump to character creation (but not nest this if statement even further)
{
I want to apply this idea to a solved problem which I have already asked before:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.CursorVisible = false;
int iMOP = 1;
Console.WriteLine(" >>New Game");
Console.WriteLine(" Load Game");
Console.WriteLine(" Exit Game");
while (iMOP != 5)
{
{
ConsoleKeyInfo keyInfo = Console.ReadKey();
if (keyInfo.Key == ConsoleKey.UpArrow)
{
iMOP--;
}
else if (keyInfo.Key == ConsoleKey.DownArrow)
{
iMOP++;
}
}
if (iMOP == 0)
{
iMOP = 3;
}
else if (iMOP == 4)
{
iMOP = 1;
}
switch (iMOP)
{
case 1:
Console.Clear();
Console.WriteLine(" >>New Game");
Console.WriteLine(" Load Game");
Console.WriteLine(" Exit Game");
break;
case 2:
Console.Clear();
Console.WriteLine(" New Game");
Console.WriteLine(" >>Load Game");
Console.WriteLine(" Exit Game");
break;
case 3:
Console.Clear();
Console.WriteLine(" New Game");
Console.WriteLine(" Load Game");
Console.WriteLine(" >>Exit Game");
break;
}
}
}
}
The questions would be: How do I realize this? Are there decent tutorials which you could link me to?
If it is going to get too complicated, use a Console based Graphics engine (Is there any console "graphics" library for .Net?).
MonoCurses seem to be very friendly: http://www.mono-project.com/docs/tools+libraries/libraries/monocurses/
But, just for curiosity, something much simpler (from scratch):
Use Classes to Create, Display and Get the user input for your menu.
How it works
It is basically a Menu Class, that displays its MenuItem classes, and draw while wait the user select a option.
This menu class was then inserted in a nested Switch, for the Main Menu levels.
I tried to do something better, needs refactoring, so you can have some idea to improve:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication22
{
class Program
{
static void Main(string[] args)
{
do
{
#region Main Menu
var m = new Menu() { Title = "MAIN MENU" };
m.Menus.Add(new MenuItem() { Title = "New Game", SelectedForegroundColor = ConsoleColor.Green });
m.Menus.Add(new MenuItem() { Title = "Load Game" });
m.Menus.Add(new MenuItem() { Title = "Exit Game", SelectedForegroundColor = ConsoleColor.Yellow });
var result = m.ShowAndWaitUserInput();
//Console.Write("selected was:" + result);
//Console.ReadLine();
#endregion
switch (result)
{
case 0:
#region // Jump to character creation
var m1 = new Menu() { Title = "CHARACTER CREATION" };
m1.Menus.Add(new MenuItem() { Title = "New Character" });
m1.Menus.Add(new MenuItem() { Title = "Load Character" });
m1.Menus.Add(new MenuItem() { Title = "Return" });
var result1 = m1.ShowAndWaitUserInput();
switch (result1)
{
case 0:
#region // CREATE THE NEW CHARACTER
Console.WriteLine("CREATE THE NEW CHARACTER");
Console.ReadKey();
#endregion
break;
case 1:
#region // LOAD CHARACTER
Console.WriteLine("LOAD CHARACTER");
Console.ReadKey();
// Write your code here...
#endregion
break;
case 2:
#region // DO ALMOST NOTHING: RETURNS TO PREVIOUS MENU
#endregion
break;
}
#endregion
break;
case 1:
#region // Load Game code...
Console.WriteLine("LOAD GAME");
Console.ReadKey();
// Write your code here...
#endregion
break;
case 2:
#region // EXIT GAME
#endregion
return;
}
} while (true); // Main Menu
}
}
public class MenuItem
{
public string Title { get; set; }
public ConsoleColor SelectedForegroundColor { get; set; }
public MenuItem()
{
this.SelectedForegroundColor = ConsoleColor.Yellow;
}
}
public class Menu
{
public string Title { get; set; }
public List<MenuItem> Menus { get; set; }
public Menu()
{
this.Menus = new List<MenuItem>();
}
public int ShowAndWaitUserInput()
{
Console.CursorVisible = false;
int selectedMenu = 0;
do
{
Console.Clear();
#region Display Menu and Sub-Menus
{
var i = 0;
// more at http://www.graphics.cornell.edu/~westin/misc/windows_charmap.html
Console.WriteLine(" ╔═══════════════════════════════════════════╗");
Console.WriteLine(" ║ ░ " + this.Title.ToUpper().PadRight(40).Substring(0, 40) + "║");
Console.WriteLine(" ╚═══════════════════════════════════════════╝");
Console.WriteLine("");
//var old_CB = Console.BackgroundColor;
var old_CF = Console.ForegroundColor;
foreach (var menu in Menus)
{
//Console.WriteLine(" New Game");
if (i == selectedMenu)
{
Console.ForegroundColor = menu.SelectedForegroundColor;
Console.Write(" >> ");
}
else
{
Console.ForegroundColor = old_CF;
Console.Write(" ");
}
Console.WriteLine(menu.Title);
i++;
}
Console.WriteLine("");
//Console.BackgroundColor = old_CB;
Console.ForegroundColor = old_CF;
}
#endregion
#region Get User Input
{
ConsoleKeyInfo keyInfo = Console.ReadKey();
if (keyInfo.Key == ConsoleKey.UpArrow)
{
selectedMenu--;
if (selectedMenu < 0) selectedMenu = Menus.Count() - 1;
}
else if (keyInfo.Key == ConsoleKey.DownArrow)
{
selectedMenu++;
if (selectedMenu == Menus.Count()) selectedMenu = 0;
}
else if (keyInfo.Key == ConsoleKey.Enter)
{
return selectedMenu;
}
}
#endregion
} while (true);
}
}
}

How to loop this?

Im having trouble learning how to loop, and Im stuck on how to do this. Basically I was asked to program that rolls a 6 sided die and it'll ask you how many times you want to roll it. Based on how many times you roll, it will out put a table of how many times it landed on each side. This is what I have so far.
using System;
namespace Dice
{
class Program
{
static void Main(string[] args)
{
bool continueRunning = true;
int sessionNumber = 1;
DisplayInstructions();
while (continueRunning)
{
int howMany = int.Parse(getInfo("How many times do you want to roll the die?"));
Dice aDice = new Dice();
aDice.RollDice();
Console.Clear();
Console.WriteLine("Session Number: {0}", sessionNumber);
Console.WriteLine(aDice);
continueRunning = getYorN("Would you like to run again?");
sessionNumber++;
Console.Clear();
}
}
public static bool getYorN(string question)
{
bool validInput = false;
while (!validInput)
{
Console.WriteLine("{0}", question);
Console.WriteLine("Enter 'yes' or 'no' to continue...");
string userResponse = Console.ReadLine().ToLower();
if (userResponse == "yes" || userResponse == "no")
{
validInput = true;
switch (userResponse)
{
case "yes":
return true;
case "no":
return false;
default:
return false;
}
}
else
{
Console.Clear();
Console.WriteLine("You've entered an invalid term");
}
}
return false;
}
public static void DisplayInstructions()
{
Console.WriteLine("Welcome to the Dice Game!!");
Console.WriteLine("\n\n\nThis program will simulate rolling a die and will track the frequency \neach value is rolled.");
Console.WriteLine("\n\n\nAfter rolling the die, the program will output a summary table for the session.");
Console.WriteLine("\n\n\nPlease press any key to continue.");
Console.ReadKey();
Console.Clear();
}
public static string getInfo(string what)
{
Console.WriteLine(what);
return Console.ReadLine();
}
}
}
The class I have in this is
using System;
namespace TripCalcApp
{
class Dice
{
private int side1 = 0, side2 = 0, side3 = 0, side4 = 0, side5 = 0, side6 = 0;
Random randNum = new Random();
public Dice()
{
}
public int Side1
{
get { return side1; }
set { side1 = value; }
}
public int Side2
{
get { return side2; }
set { side2 = value; }
}
public int Side3
{
get { return side3; }
set { side3 = value; }
}
public int Side4
{
get { return side4; }
set { side4 = value; }
}
public int Side5
{
get { return side5; }
set { side5 = value; }
}
public int Side6
{
get { return side6; }
set { side6 = value; }
}
public void RollDice()
//RollDice = randNum.Next(1, 7)
{
switch (randNum.Next(1, 7))
{
case 1: side1++;
break;
case 2: side2++;
break;
case 3: side3++;
break;
case 4: side4++;
break;
case 5: side5++;
break;
case 6: side6++;
break;
}
}
public override string ToString()
{
return " Freq. Rolls " +
"________________________________________" +
"\nSide 1 of Die rolled :" + side1 +
"\nSide 2 of Die rolled :" + side2 +
"\nSide 3 of Die rolled :" + side3 +
"\nSide 4 of Die rolled :" + side4 +
"\nSide 5 of Die rolled :" + side5 +
"\nSide 6 of Die rolled :" + side6 +
"\n";
}
}
}
I had an idea on how to do loop it but Im still unsure. I thought of something like this but it doesnt work and I was hoping you guys could help me!!
int howMany = int.Parse(getInfo("How many times would you like to roll the die?"));
do
{
Dice aDice = new Dice();
for (int counter = howMany; counter > 0; counter--)
{
aDice.RollDice();
}
while (howMany < 0)
{
Console.WriteLine(aDice);
}
Console.Clear();
Console.WriteLine("Session Number: {0}", sessionNumber);
Console.WriteLine(aDice);
playAgain = getYorN("Would you like to play again?");
sessionNumber++;
}
All you need to do is call aDice.RollDice method howMany times:
while (continueRunning)
{
int howMany = int.Parse(getInfo("How many times do you want to roll the die?"));
Dice aDice = new Dice();
for(int i = 0; i < howMany; i++)
{
aDice.RollDice();
}
Console.Clear();
Console.WriteLine("Session Number: {0}", sessionNumber);
Console.WriteLine(aDice);
continueRunning = getYorN("Would you like to run again?");
sessionNumber++;
Console.Clear();
}

Categories