I'm creating this Blackjack game and I'm having trouble calculating the total value of both the dealer and player. I've created a method to calculate the value for both the player(PlayerTotalCalculate) and the dealer (DealerTotalCalculate) using forloops.
When I run the program, the first sequence of cards are added up correctly, but when I "HIT" to get a new card for the player, it takes the previous value shown and adds the new card given as well as the value of the 2 cards given previously..
using System;
using System.Collections.Generic;
namespace BlackJack2
{
internal class Program
{
//GLOBAL VARIABLES
static List<Card> myListOfCards = new List<Card>();
static List<Card> dealersHand = new List<Card>();
static List<Card> playersHand = new List<Card>();
enum Phase { StartGame, DealersFirst, PlayersTurn, DealersTurn, ChooseWinner, End }
static Phase currentPhase;
static int userInput;
static void Main(string[] args)
{
string suitFace = "";
int dealersTotalValue = 0;
int playersTotalvalue = 0;
//Creating the list of cards
for (int i = 0; i < 4; i++)
{
switch (i)
{
case 0:
suitFace = "Diamonds";
break;
case 1:
suitFace = "Spades";
break;
case 2:
suitFace = "Hearts";
break;
case 3:
suitFace = "Clubs";
break;
}
myListOfCards.Add(new Card("King", suitFace, 10));
myListOfCards.Add(new Card("Queen", suitFace, 10));
myListOfCards.Add(new Card("Jack", suitFace, 10));
myListOfCards.Add(new Card("10", suitFace, 10));
myListOfCards.Add(new Card("9", suitFace, 9));
myListOfCards.Add(new Card("8", suitFace, 8));
myListOfCards.Add(new Card("7", suitFace, 7));
myListOfCards.Add(new Card("6", suitFace, 6));
myListOfCards.Add(new Card("5", suitFace, 5));
myListOfCards.Add(new Card("4", suitFace, 4));
myListOfCards.Add(new Card("3", suitFace, 3));
myListOfCards.Add(new Card("2", suitFace, 2));
myListOfCards.Add(new Card("Ace", suitFace, 1));
}
for (int i = 0; i < playersHand.Count; i++)
{
playersHand.Remove(playersHand[i]);
}
for (int i = 0; i < dealersHand.Count; i++)
{
dealersHand.Remove(dealersHand[i]);
}
//Assigning the first phase
currentPhase = Phase.DealersFirst;
DealersTurn(dealersTotalValue, playersTotalvalue);
}
//Deal Card Method using Random Number Generator
static void DealCard(int dealerTotalValue, int playersTotalValue)
{
Random r = new Random();
int randomNumber = r.Next(0, myListOfCards.Count);
if (currentPhase == Phase.DealersFirst || currentPhase == Phase.DealersTurn)
{
dealersHand.Add(myListOfCards[randomNumber]);
}
else if (currentPhase == Phase.PlayersTurn)
{
playersHand.Add(myListOfCards[randomNumber]);
//PlayerTotalCalulate(ref playersTotalValue);
}
myListOfCards.RemoveAt(randomNumber);
}
//Determining dealer's actions
static void DealersTurn(int dealersTotalvalue, int playersTotalValue)
{
if (currentPhase == Phase.DealersFirst)
{
for (int i = 0; i < 1; i++)
{
DealCard(dealersTotalvalue, playersTotalValue);
DealerTotalCalculate(ref dealersTotalvalue);
}
DisplayDealerCards();
Console.WriteLine($"The dealer has a total value of: {dealersTotalvalue}");
currentPhase = Phase.PlayersTurn;
PlayersTurn(dealersTotalvalue, playersTotalValue);
}
else if (currentPhase == Phase.DealersTurn)
{
while (dealersTotalvalue < 15)
{
DealCard(dealersTotalvalue, playersTotalValue);
DealerTotalCalculate(ref dealersTotalvalue);
DisplayDealerCards();
Console.WriteLine($"The dealer's new total is: {dealersTotalvalue}");
}
CalculateWinner(dealersTotalvalue, playersTotalValue);
}
}
static void PlayersTurn(int dealersTotalValue, int playersTotalValue)
{
for (int i = 0; i < 2; i++)
{
DealCard(dealersTotalValue, playersTotalValue);
}
PlayerTotalCalulate(ref playersTotalValue);
DisplayPlayerCards(playersTotalValue);
Console.WriteLine($"You have a total value of: {playersTotalValue}");
while (currentPhase == Phase.PlayersTurn)
{
Console.WriteLine("Would you like to hit or stay?");
Console.WriteLine("1: HIT or 2: STAY");
int.TryParse(Console.ReadLine(), out userInput);
if (userInput == 1)
{
DealCard(dealersTotalValue, playersTotalValue);
PlayerTotalCalulate(ref playersTotalValue);
DisplayPlayerCards(playersTotalValue);
Console.WriteLine($"You now have a total value of: {playersTotalValue}");
}
else if (userInput == 2)
{
currentPhase = Phase.DealersTurn;
DealersTurn(dealersTotalValue, playersTotalValue);
}
else
{
Console.WriteLine("Invalid input! Please try again.");
}
}
}
static void DisplayPlayerCards(int playersTotalValue)
{
for (int i = 0; i < playersHand.Count; i++)
{
Console.WriteLine($"You were dealt a(n): {playersHand[i].DisplayCard()}");
}
PlayerTotalCalulate(ref playersTotalValue);
}
static void DisplayDealerCards()
{
//Showing only one card from the dealer
for (int i = 0; i < dealersHand.Count; i++)
{
Console.WriteLine($"The dealer is showing: {dealersHand[i].DisplayCard()}. The other card is hidden.");
}
}
static void CalculateWinner(int dealersTotalvalue, int playersTotalValue)
{
if (playersTotalValue > dealersTotalvalue && playersTotalValue < 21)
{
Console.WriteLine($"Your Total: {playersTotalValue}");
Console.WriteLine($"Dealer's Total: {dealersTotalvalue}");
Console.WriteLine("Great job! You've won!");
Console.WriteLine("Press ENTER to play again!");
Console.ReadKey();
}
else if (playersTotalValue == dealersTotalvalue)
{
Console.WriteLine($"Your Total: {playersTotalValue}");
Console.WriteLine($"Dealer's Total: {dealersTotalvalue}");
Console.WriteLine("The game is a tie!");
Console.WriteLine("Press ENTER to play again!");
Console.ReadKey();
}
else if (playersTotalValue < dealersTotalvalue && playersTotalValue > 21)
{
Console.WriteLine($"Your Total: {playersTotalValue}");
Console.WriteLine($"Dealer's Total: {dealersTotalvalue}");
Console.WriteLine("Oh no! You've lost!");
Console.WriteLine("Press ENTER to play again!");
Console.ReadKey();
}
//Console.WriteLine(PlayerTotalCalulate(ref playersTotalValue));
}
static void PlayerTotalCalulate(ref int playersTotalValue)
{
for (int i = 0; i < playersHand.Count; i++)
{
playersTotalValue += playersHand[i].Value;
}
}
static void DealerTotalCalculate(ref int dealersTotalValue)
{
for (int i = 0; i < dealersHand.Count; i++)
{
dealersTotalValue += dealersHand[i].Value;
}
}
static void DisplayAllCards()
{
for (int i = 0; i < myListOfCards.Count; i++)
{
Console.WriteLine(myListOfCards[i].DisplayCard());
Console.WriteLine("\n\r\t");
}
}
static void DisplayingSingleCard()
{
Console.WriteLine(myListOfCards[0].DisplayCard());
}
}
}
I've also provided a screenshot of the console itself.
ConsolePicture
In DealerTotalCalculate, you should set dealersTotalValue to 0 before you add up the cards.
You need to do that in PlayerTotalCalulate as well.
As said in my comment, it's because your total variable is never reseted. So when you call the method to add the new value, it takes also the old value into consideration. So you just need to do total = 0, before calling the compute method.
Also consider this to simplify your compute method :
int[] array = { 1, 2, 3, 4, 5 };
int sum = array.Sum();
Console.WriteLine(sum);
It's slightly better, regarding code readability in my opinion. Not a big deal at all.
Related
I keep on receiving this CS0136 error and I'm unsure why?
using System;
namespace Lab2_1
{
class Program
{
static void Main(string[] args)
{
Action<string> cw = Console.WriteLine;
int[] numbers = new int[10];
int currentIndex = 0;
bool repeat = true;
do
{
cw("Please enter an interger: ");
string line = Console.ReadLine();
if (line == "exit")
{
repeat = false;
}
else
{
try
{
int number = int.Parse(line);
cw("The number you entered was: " + number);
numbers[currentIndex] = number;
currentIndex++;
}
catch (FormatException)
{
cw("That wasn't a number!");
}
}
} while (repeat);
Console.WriteLine("Press any key to exit.");
{
while (repeat) ;
for (int i = 0; i < currentIndex; i++)
{
Console.WriteLine(numbers[i]);
}
currentIndex++;
if (currentIndex == numbers.Length)
{
int expandedNumberOfCells = currentIndex + 10;
}
int expandedNumberOfCells = currentIndex + 10;
int[] expandedNumbers = new int[expandedNumberOfCells];
for (int i = 0; i < currentIndex; i++)
{
expandedNumbers[i] = numbers[i];
}
numbers = expandedNumbers;
}
}
}
}
From this page you can see what error CS0136 is.
You could not declare expandedNumberOfCells repeatedly, you can slightly modify your code:
int expandedNumberOfCells = currentIndex + 10;
int[] expandedNumbers = new int[expandedNumberOfCells];
if (currentIndex == numbers.Length)
{
expandedNumberOfCells = currentIndex + 10;
}
for (int i = 0; i < currentIndex; i++)
{
expandedNumbers[i] = numbers[i];
}
numbers = expandedNumbers;
This question already has an answer here:
How can i check the winner in the my Connect four java code? [closed]
(1 answer)
Closed 4 years ago.
I got an assignment to program connect-4 in console. I have already programmed the board, but I am having a very hard time calculating the winner.
This is what I got so far:
// Array play board
int[,] intRaster = new int[6,7];
// playboard
Console.WriteLine("\n\n\t\t\t 1 2 3 4 5 6 7\n");
string strTab = "\t\t\t\t";
// Displays playboard
for (int intX = 0; intX < 6; intX++)
{
Console.Write(strTab);
for (int intY = 0; intY < 7; intY++)
{
Console.Write(intRaster[intX, intY]);
Console.Write(" ");
}
Console.WriteLine();
}
// Input
Label_0:
Console.Write(" \n\n\t\t\t Speler 1: Maak uw zet!");
// Player 1
switch (Console.ReadKey(true).KeyChar.ToString())
{
case "1":
Console.Write("1");
if (intRaster[0, 0] < 6)
{
intRaster[0, 0]++;
Console.SetCursorPosition(32, 13 - intRaster[0, 0]);
Console.Write("1");
Console.SetCursorPosition(60, 13);
}
// Gives error message if player tries to put a disk in a
// full colom
else
{
Console.SetCursorPosition(60, 13);
Console.Write(" \n\n\t\t\t ERROR: rij is vol!!!");
Console.ReadKey();
Console.SetCursorPosition(60, 13);
goto Label_0;
}
// Player 2
Label_1:
Console.Write(" \n\n\t\t\t Speler 2: Maak uw zet!");
switch (Console.ReadKey(true).KeyChar.ToString())
{
case "1":
Console.Write("1");
if (intRaster[0, 0] < 6)
{
intRaster[0, 0]++;
Console.SetCursorPosition(32, 13 - intRaster[0, 0]);
Console.Write("2");
Console.SetCursorPosition(60, 13);
}
else
{
Console.SetCursorPosition(60, 13);
Console.Write(" \n\n\t\t\t ERROR: rij is vol!!!");
Console.ReadKey();
Console.SetCursorPosition(60, 13);
goto Label_1;
}
goto Label_0;
So what I basicly did was declaring a 2 dimensional integer array [6,7].
The for loop will display the gameboard with the values of the array (which at the start would be 0 for every value).
Then the switch will read de character input of the player. If player 1 presses 1 the value 0 ([6, 0]) will be replaced by 1 etc...
Of course the switch contains more cases, but I left those out to shorten this code. So how do I calculate the winner horizontal, vertical and diagonally?
Any help will be much appreciated!
Here you are, I got overexcited.. :-)
class Game
{
static int[,] intRaster = new int[6, 7];
static int[] positionsDiskCount = new int[7];
public static void Main()
{
// Array play board
// playboard
Console.WriteLine("\n\n\t\t\t 1 2 3 4 5 6 7\n");
string strTab = "\t\t\t\t";
// Displays playboard
for (int intX = 0; intX < 6; intX++)
{
Console.Write(strTab);
for (int intY = 0; intY < 7; intY++)
{
Console.Write(intRaster[intX, intY]);
Console.Write(" ");
}
Console.WriteLine();
}
// Input
while (true)
{
MakeMove(1);
MakeMove(2);
}
}
static private int MakeMove(int Player)
{
Console.Write(" \n\n\t\t\t Speler {0}: Maak uw zet! ", Player);
int num = -1;
bool moveMade = false;
while (!moveMade)
{
while (true)
{
string key = Console.ReadKey(true).KeyChar.ToString();
if (key == "\u001b") Environment.Exit(0);
if (int.TryParse(key, out num) && num > -1 && num < 8) break;
}
num--;
if (positionsDiskCount[num] < 6)
{
intRaster[num, positionsDiskCount[num]] = Player;
Console.SetCursorPosition(32 + num * 2, 9 - positionsDiskCount[num]);
Console.Write(Player);
Console.SetCursorPosition(60, 10);
bool win = CheckWinner(num, positionsDiskCount[num]);
if (win)
{
Console.WriteLine(" \n\n\t\t\t Speler {0} has won the game!!!!!!", Player);
Console.WriteLine("Press any key to exit");
Console.ReadKey(true).KeyChar.ToString();
Environment.Exit(0);
}
positionsDiskCount[num]++;
moveMade = true;
}
else
{
Console.SetCursorPosition(60, 10);
Console.Write(" \n\n\t\t\t ERROR: rij is vol!!! Maak uw zet!");
Console.ReadKey();
Console.SetCursorPosition(60, 10);
}
}
return num;
}
static public bool CheckWinner(int x, int y)
{
//Horizontal
int count = countDirection(x, y, -1, 0);
count += countDirection(x, y, 1, 0);
if (count > 2) return true;
count = countDirection(x, y, 0, -1);
count += countDirection(x, y, 0, 1);
if (count > 2) return true;
count = countDirection(x, y, -1, -1);
count += countDirection(x, y, 1, 1);
if (count > 2) return true;
count = countDirection(x, y, 1, -1);
count += countDirection(x, y, -1, 1);
if (count > 2) return true;
return false;
}
static public int countDirection(int x, int y, int stepX, int stepY)
{
int count = 0;
int Player = intRaster[x, y];
x += stepX;
y += stepY;
while (x >= 0 && x < intRaster.GetUpperBound(1) && y >= 0 && y < intRaster.GetUpperBound(0))
{
if (Player == intRaster[x, y]) count++;
else break;
x += stepX;
y += stepY;
}
return count;
}
}
I am new at programming and I'm trying to understand why the methods call inside a switch statement is not working. Basically I have a main menu and a submenu. Whem I press the Animal submenu , the switch statement is meant to call the methods for a CRUD (insert new, visualize by Id, update, etc) but none of these options are working. Is the method call/structure correct?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace menu_clinica_veterinaria
{
class Program
{
public static int id = 1;
enum animalHeader { id, name, client_name, type_animal };
enum clientHeader { id, name, client_surname, adrress };
static void Main(string[] args)
{
string[,] animal = new string[20, 4];
string[,] client = new string[20, 6];
do { MenuOptions(animal); } while (true);
}
static void MenuOptions(string[,] animal)
{
int userChoice;
do
{
Console.Clear();
Console.WriteLine("\nChoose one of the following options:\n");
Console.WriteLine("[ 1 ] Animals");
Console.WriteLine("[ 2 ] Clients");
Console.WriteLine("[ 0 ] Quit application\n");
} while (!int.TryParse(Console.ReadLine(), out userChoice) || userChoice < 0 || userChoice > 2);
Console.Clear();
switch (userChoice)
{
case 1:
menuAnimal(animal);
break;
case 2:
//menuClient(client);
break;
case 0:
Environment.Exit(0);
break;
default:
Console.WriteLine("Try again!!");
break;
}
}
static void menuAnimal(string[,] animal)
{
int optAnimal;
while (true)
{
do
{
Console.Clear();
Console.WriteLine("\nInsert one of the following options:\n");
Console.WriteLine("[ 1 ] Insert animal");
Console.WriteLine("[ 2 ] See animal");
Console.WriteLine("[ 3 ] Alter animal");
Console.WriteLine("[ 4 ] Erase animal");
Console.WriteLine("[ 5 ] List animals");
Console.WriteLine("[ 0 ] Return to main menu\n");
} while (!int.TryParse(Console.ReadLine(), out optAnimal) || optAnimal < 0 || optAnimal > 5);
Console.Clear();
bool goBack = false;
switch (optAnimal)
{
case 1:
insertData(animal);
break;
case 2:
visualizeByid(animal);
break;
case 3:
updateById(animal);
break;
case 4:
deleteByid(animal);
break;
case 5:
listData(animal);
break;
case 0:
goBack = true;
break;
}
if (goBack) return;
}
}
static void mainMenu()
{
Console.Clear();
Console.ReadKey();
}
static void menuReturn(string[,] animal)
{
Console.Clear();
do { menuAnimal(animal); } while (true);
}
static int generateId()
{
return id++;
}
static int getInsertIndex(string[,] matrix)
{
for (int j = 0; j < matrix.GetLength(0) - 1; j++)
{
if (string.IsNullOrEmpty(matrix[j, 0])) return j;
}
return -1;
}
static void insertData(string[,] matrix)
{
int id = generateId();
int n = getInsertIndex(matrix);
matrix[n, 0] = Convert.ToString(id);
for (int j = 1; j < matrix.GetLength(1); j++)
{
do
{
Console.Write($"Insert {Enum.GetName(typeof(animalHeader), j)}: ");
matrix[n, j] = Console.ReadLine();
} while (String.IsNullOrEmpty(matrix[n, j]));
}
}
static int searchId(string[,] matrix)
{
int choosenId, index = -1;
do
{
Console.Write("Insert ID to continue: ");
} while (!int.TryParse(Console.ReadLine(), out choosenId));
for (int i = 0; i < matrix.GetLength(0); i++)
{
if (Convert.ToString(choosenId) == matrix[i, 0])
{
index = i;
}
}
return index;
}
static void visualizeByid(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write($"{matrix[i, j]}\t");
}
Console.WriteLine();
}
}
else { Console.WriteLine("Wrong Id"); }
}
static void updateById(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 1; j < matrix.GetLength(1); j++)
{
Console.Write($"Insert {Enum.GetName(typeof(animalHeader), j)}: ");
matrix[i, j] = Console.ReadLine();
}
Console.WriteLine();
}
}
else { Console.WriteLine("Id does not exist"); }
}
static void deleteByid(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i, j] = null;
}
}
}
else { Console.WriteLine("Id does not exist"); }
}
static void listData(string[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write($"\t{matrix[i, j]}\t");
}
Console.WriteLine("\n\t");
}
}
}
}
It's a nifty little program for what it is.
However, you can't see an animal because:
searchId
for (var i = 0; i < matrix.GetLength(0); i++)
{
if (Convert.ToString(choosenId) == matrix[i, 0])
{
index = i;
// Though it's not the problem you could break here
// you could also just return from here
break;
}
}
Also, you'll need to Console.ReadKey() somewhere as your menu refreshes and overwrites the see animal routine.
menuAnimal
visualizeByid(animal);
// if you don't do something like this as the menu refreshes the animal away
Console.ReadKey();
The only other thing I'd suggest is to use lists and well-typed classes, instead of multidimensional arrays of strings; they are easier to work with, and you can use Linq.
Update
In regards to comments, given this:
private static string GetHeader<T>(int i) => Enum.GetName(typeof(T), i);
You could do something like this:
static void updateById<T>(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 1; j < matrix.GetLength(1); j++)
{
Console.Write($"Insert {GetHeader<T>(j)}: ");
...
Usage:
updateById<animalHeader>(animal);
Basically this is some generics to reuse the updateById method and using your HeaderType.
Your program working Fine. You are using Console.Clear(). It will clear the screen which is displayed previously on the screen. Remove Console.Clear() in the program or Add Console.ReadKey() immediately after Switch block. I think it will work fine.
Im taking and Into c# course and Im having alot of fun learning, however Im getting stuck on this one assignment--I have to simulate rolling a 6 sided dice/die 500 times (user must input the number of rolls) while displaying the frequency of each side(1-6) and % roll. In addition I cant use arrays.
So To start what I did was Initiate a bool to loop my code because I have to ask the user if they want to roll again. Then I created a variable for dice1 and set it to a Random number between 1-6. I tried setting a variable to a console readline that was equal to the dice1 to have the user enter the number. This is pretty much where I get stuck and cant move forward.
I know many of you are much more knowledgeable than I am so It'd be great If anyone could give me some advice.
Here's what I have so far:
static void Main(string[] args)
{
//Initiate Looping Seqence
bool choice = true;
while (choice)
{
//Display Introduction and Instructions
Console.WriteLine("Welcome To The Dice Game!");
Console.WriteLine("This Program will simulate rolling a die and will track");
Console.WriteLine("the Frequency each value is rolled Then Display a Session Summary");
Console.WriteLine("Press any key to continue.....");
Console.ReadKey();
Console.Clear();
Console.WriteLine("How many times would you like to roll the die?");
Random randomNum = new Random();
int dice1;
dice1 = randomNum.Next(1, 7);
int choice2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
Console.WriteLine(dice1);
int s1 = 0;
int s2 = 0;
int s3 = 0;
int s4 = 0;
int s5 = 0;
int s6 = 0;
Console.WriteLine("Would you Like to Run This Program Again?");
Console.WriteLine("Type \"yes\" to re-run or Type \"no\" to exit?");
Console.ReadKey();
string option;
option = Console.ReadLine();
}
}
// public static double RollDice()
//{
// was not sure if to create a dice roll method
//}
}
}
Have a break, take my code ヽ(^o^)丿
class Program {
#region lambda shortcuts
static Action<object> Warn = m => {
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(m);
};
static Action<object> Info = m => {
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(m);
};
static Action<object> WriteQuery = m => {
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(m);
};
static Action BreakLine = Console.WriteLine;
#endregion
static void Main(string[] args) {
Console.Title = "The Dice Game";
while(true) {
bool #continue = RunDiceGame();
if(!#continue) {
break;
}
Console.Clear();
}
}
static bool RunDiceGame() {
//Display Introduction and Instructions
Info("Welcome To The Dice Game!");
Info("This Program will simulate rolling a dice and keeps track of the results");
BreakLine();
WriteQuery("Dice roll count: ");
int rollCount = ReadInt32();
WriteQuery("Random number generator seed: ");
Random rng = new Random(ReadInt32());
BreakLine();
BreakLine();
//map dice value to dice count
var diceValues = new Dictionary<int, int>((int)rollCount);
for(int i = 0; i < 6; i++) {
diceValues.Add(i, 0);
}
//roll dice
for(int i = 0; i < rollCount; i++) {
int diceValue = rng.Next(6); //roll 0..5
diceValues[diceValue]++;
}
//print results
for(int i = 0; i < 6; i++) {
int valueRollAbsolute = diceValues[i];
double valueRollCountRelative = valueRollAbsolute / (double) rollCount;
Info(string.Format("Value: {0}\tCount: {1:0,0}\tPercentage: {2:0%}", i + 1, valueRollAbsolute, valueRollCountRelative));
}
BreakLine();
BreakLine();
WriteQuery("Type 'yes' to restart, 'no' to exit.");
BreakLine();
return ReadYesNo();
}
#region console read methods
static int ReadInt32() {
while(true) {
string input = Console.ReadLine();
try {
return Convert.ToInt32(input);
} catch(FormatException) {
Warn("Not a number: " + input);
}
}
}
static bool ReadYesNo() {
while(true) {
string option = Console.ReadLine();
switch(option.ToLowerInvariant()) {
case "yes":
return true;
case "no":
return false;
default:
Warn("Invalid option: " + option);
break;
}
}
}
#endregion
}
Here is some code to simulate the rolls & get how many times a number popped up
int rollAmount = 500;
int dice;
int s1 = 0;
int s2 = 0;
int s3 = 0;
int s4 = 0;
int s5 = 0;
int s6 = 0;
Random random = new Random();
for(int i = 0; i <= rollAmount; i++){
dice = random.next(1,7);
Console.Writeline("Roll " + i + ": " + dice.ToString());
if(dice == 1) s1++;
else if(dice == 2) s2++;
else if(dice == 3) s3++;
...
}
Console.Writeline("1 Percentage: " + ((s1 / rollAmount) * 100) + "%");
Console.Writeline("2 Percentage: " + ((s2 / rollAmount) * 100) + "%");
Console.Writeline("3 Percentage: " + ((s3 / rollAmount) * 100) + "%");
...
Console.Writeline("Done");
I want to enter 10 numbers, and then show them in 1 line like this:
1,4,5,2,456,23,... and so on..
and it keeps writing them as I am entering them, and in the end when it's supposed to show all numbers in 1 line it shows only the last one.
I know it's possible with random numbers but when I enter them on my own I don't know how not to show them at all or keep them in 1 line and if it is even possible?
int a;
int x;
Console.WriteLine("a:");
a = int.Parse(Console.ReadLine());
x = 10;
for (int i = 0; i < x; i++)
{
a = int.Parse(Console.ReadLine());
}
Console.ReadKey();
you can use
Console.ReadKey(true)
it reads a key from console and does not show it.
you can use this to read word from console without showing it
public static string ReadHiddenFromConsole()
{
var word = new StringBuilder();
while (true)
{
var i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
if (i.Key == ConsoleKey.Backspace)
{
if (word.Length > 0)
{
word.Remove(word.Length - 1, 1);
Console.Write("\b \b");
}
}
else
{
word.Append(i.KeyChar);
Console.Write("*");
}
}
return word.ToString();
}
You can use this code:
static void Main(string[] args)
{
int length = 10;
int[] myNumbers = new int[length];
for (int i = 0; i < length; i++)
{
Console.Write("Enter number:" );
myNumbers[i] = Convert.ToInt32(Console.ReadLine());
Console.Clear();
}
Console.WriteLine("Your numbers: {0}", string.Join(",", myNumbers));
}
i dont know how to write them at the end all in 1 line?
Well you need to save them as they are entered:
int num;
var nums = new List<int>();
while (nums.Count < 10)
{
Console.Write("Enter: ");
if (int.TryParse(Console.ReadLine(), out num))
{
nums.Add(num);
Console.Clear();
}
}
Console.WriteLine(string.Join(", ", nums));