I'm stuck on how I can implement the code so when it compiles to one counter it displays one counter not 'counters' as a plural for only one counter. I need help on how I can implement that piece of code in to my code that I have given below.
namespace ReferralDG
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Even Minus Odd Game: ");
Random rand = new Random();
bool PlayAgain = false;
do
{
int numberOfDice = 0;
int totalOfDiceRolled = 0;
while (numberOfDice > 10 || numberOfDice < 3)
{
Console.WriteLine("How many dice do you wish to play with? (Between 3 and 10?)");
numberOfDice = Convert.ToInt32(Console.ReadLine());
if (numberOfDice > 10 || numberOfDice < 3)
{
Console.WriteLine("Please enter the correct number
}
}
Console.Write("Dice rolls: ");
int evenTotal = 0;
int oddTotal = 0;
for (int i = 0; i < numberOfDice; i++)
{
int diceRoll = rand.Next(1, 7);
if (diceRoll % 2 == 0)
{
evenTotal += diceRoll;
}
else
{
oddTotal += diceRoll;
}
totalOfDiceRolled += diceRoll;
Console.Write(diceRoll + " ");
}
int counters = evenTotal - oddTotal;
Console.WriteLine();
if (counters > 0)
{
Console.WriteLine("You take " + counters + " counters.");
}
else if (counters < 0)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counters.");
}
else if (evenTotal == oddTotal)
{
Console.WriteLine("Even total is equal to odd total");
}
else
{
Console.WriteLine("No counters this game");
}
Console.WriteLine("Would you like to play again? (Y/N): ");
string playAgain = Console.ReadLine().ToUpper();
if (playAgain == "Y")
{
PlayAgain = true;
}
else
{
PlayAgain = false;
}
} while (PlayAgain);
}
}
}
you could use the if shorthand statement ? valueIfTrue : valueIfFalse; to set the right string values. and put everything in a function like that
private static void printCounters(int counters,bool take) {
counters = Math.Abs(counters);
string msg1 = take ? "You take " : "You give ";
string msg2 = counters == 1 ? " counter." : " counters.";
Console.WriteLine( msg1 + counters + msg2);
}
this has the advantage that you can easily call printCounters(counters,true) if you take and printCounters(counters,give) if you give
You can just add additional if's to your block.
if (counters > 1) {
Console.WriteLine("You take " + counters + " counters.");
}
else if (counters > 0) // or if you rather counters == 1
{
Console.WriteLine("You take " + counters + " counter.");
}
else if (counters < -1)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counters.");
}
else if (counters < 0)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counter.");
}
else if (evenTotal == oddTotal)
{
Console.WriteLine("Even total is equal to odd total");
}
else
{
Console.WriteLine("No counters this game");
}
Another "simpler" solution is to just output it as counter(s)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
namespace ReferralDG
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Even Minus Odd Game: ");
Random rand = new Random();
bool PlayAgain = false;
do
{
int numberOfDice = 0;
int totalOfDiceRolled = 0;
while (numberOfDice > 10 || numberOfDice < 3)
{
Console.WriteLine("How many dice do you wish to play with? (Between 3 and 10?)");
numberOfDice = Convert.ToInt32(Console.ReadLine());
if (numberOfDice > 10 || numberOfDice < 3)
{
Console.WriteLine("Please enter the correct number");
}
}
Console.Write("Dice rolls: ");
int evenTotal = 0;
int oddTotal = 0;
for (int i = 0; i < numberOfDice; i++)
{
int diceRoll = rand.Next(1, 7);
if (diceRoll % 2 == 0)
{
evenTotal += diceRoll;
}
else
{
oddTotal += diceRoll;
}
totalOfDiceRolled += diceRoll;
Console.Write(diceRoll + " ");
}
int counters = evenTotal - oddTotal;
Console.WriteLine();
if (counters > 1)
{
Console.WriteLine("You take " + counters + " counters.");
}
else if (counters > 0) // or if you rather counters == 1
{
Console.WriteLine("You take " + counters + " counter.");
}
else if (counters < -1)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counters.");
}
else if (counters < 0)
{
Console.WriteLine("You give " + Math.Abs(counters) + " counter.");
}
else if (evenTotal == oddTotal)
{
Console.WriteLine("Even total is equal to odd total");
}
else
{
Console.WriteLine("No counters this game");
}
Console.WriteLine("Would you like to play again? (Y/N): ");
string playAgain = Console.ReadLine().ToUpper();
if (playAgain == "Y")
{
PlayAgain = true;
}
else
{
PlayAgain = false;
}
} while (PlayAgain);
}
}
}
}
Hello and welcome to StackOverflow Sam!
So when you write the counters to the screen, you want it to write singular if their is a single counter, and plural if there are more than 1? I also assume we want this to work no matter if the counter is positive or negative.
Instead of adding a couple more branches to your if statement, we could use string.Format() and an Inline If statement.
In this case, it would look something like this:
// Console.WriteLine("You take " + counters + " counters.");
Console.WriteLine(string.Format("You take {0} counter{1}.", counters, Math.Abs(counters) == 1 ? "" : "s"));
This is really just a way of writing multiple "else ifs", as you still have added a branching statement. My way, it is in-line instead of taking up more space vertically.
If you wanted to get even more fancy, you could use an IIF to set the "give" or "take" as well:
if (counters != 0)
{
Console.WriteLine(string.Format("You {0} {1} counter{2}.",
counters > 0 ? "take" : "give",
counters,
Math.Abs(counters) == 1 ? "" : "s"
));
}
else if (evenTotal == oddTotal)
{
Console.WriteLine("Even total is equal to odd total");
}
else
{
Console.WriteLine("No counters this game");
}
Read up on the links, see what works best for you!
Related
I am a Beginner in C# and I was wondering what I got wrong with this code.
I want the user to input the amount of numbers
Then an array with that amount gets created
Then finally I want to display all the numbers in the array.
The Code:
using System;
using System.Threading;
using System.Collections.Generic;
namespace Console_Project_alpha
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the amount of numbers: ");
int amount = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[amount];
string nth = "";
for( int i = 1; i <= amount ; i++)
{
if(i == 1)
{
nth = i + "st";
}
else if( i == 2)
{
nth = i + "nd";
}
else if( i == 3)
{
nth = i + "rd";
}else{
nth = i + "th";
}
Console.Write("\nEnter " + nth + " Number:");
int num = Convert.ToInt32(Console.ReadLine());
for(int j = 0; j <= numbers.Length; j++)
{
numbers[j] = num;
}
}
System.Console.WriteLine(numbers);
}
}
}
Any help is highly appreciated. Thanks in advance
In your code you all time overwriting the same value to all index in
array.
If you want to display values from array in console just iterate after array
Properly worked example based on your code:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the amount of numbers: ");
int amount = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[amount];
string nth = "";
int index = 0;
for (int i = 1; i <= amount; i++)
{
if (i == 1)
{
nth = i + "st";
}
else if (i == 2)
{
nth = i + "nd";
}
else if (i == 3)
{
nth = i + "rd";
}
else
{
nth = i + "th";
}
Console.Write("\nEnter " + nth + " Number:");
int num = Convert.ToInt32(Console.ReadLine());
numbers[index] = num;
index++;
}
for (int i = 0; i <= numbers.Length - 1; i++)
{
Console.WriteLine(numbers[i]);
}
Console.ReadLine();
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How to check to see if user won with a conditional?
int score1 = 0;
int score2 = 0;
int score3 = 0;
for (int i = 1; i < 11; i++)
{ //open for
if (score1 > score2 && score1 > score3) //open if
Console.WriteLine(name1 + " takes the lead in lap " + i + "!");
else if (score2 > score1 && score2 > score3)
{
Console.WriteLine(name2 + " takes the lead in lap " + i + "!");
}
else if (score3 > score2 && score3 > score1)
{
Console.WriteLine(name3 + " takes the lead in lap " + i + "!");
} //close if
} // close for
} //close if
This is the piece of code I am referring to.
So, to solve the problem, you need 3 variables to which we add the various scores at each lap, this variables are then compared before the end of the while loop. The code posted shows only the comparison for the first option. I'm sure you can figure out how to compare for the remaining options.
class Program
{
public static void Main(string[] args)
{ //open main method
string name1 = "Buck";
int endurance1 = 6;
int speed1 = 4;
string name2 = "Daisy";
int endurance2 = 4;
int speed2 = 6;
string name3 = "Leo";
int endurance3 = 7;
int speed3 = 3;
int balance = 100;
Console.WriteLine("Welcome to the racetrack!\nToday's races will include 10 laps for reach race. There will be 3 races today. \nYou have $100 you can choose to bet on one of our 3 horses.\n1. Bet on a horse. \n2. Quit the game.");
string input = Console.ReadLine();
while (input == "1")
{ //open while1
Console.WriteLine("Would you like to bet on: \n1." + name1 + ": \nEndurance:" + endurance1 + "\nSpeed:" + speed1 + "\n2." + name2 + ": \nEndurance:" + endurance2 + "\nSpeed:" + speed2 + "\n3." + name3 + ":\nEndurance:" + endurance3 + "\nSpeed:" + speed3 + "\nPlease enter the name of the horse as it appears on the screen.");
string choice = Console.ReadLine();
if (choice == "Buck")
{
Console.WriteLine("You have chosen " + name1 + ".");
}
else if (choice == "Daisy")
{
Console.WriteLine("You have chosen " + name2 + ".");
}
else
{
Console.WriteLine("You have chosen " + name3 + ".");
}
Console.WriteLine("How much would you like to bet? Your current balance is $" + balance + ".");
string money = Console.ReadLine();
int bet = int.Parse(money);
Console.WriteLine("You are betting $" + bet + " on " + choice + ". Type \'start\' to start the race.");
string race = Console.ReadLine();
int totalScore1 = 0;
int totalScore2 = 0;
int totalScore3 = 0;
if (race == "start")
{ // open if
Console.WriteLine("Let the races begin!");
for (int i = 1; i < 11; i++)
{ //open for
System.Random r = new System.Random();
int score1 = speed1 + endurance1 + r.Next(1, 8);
int score2 = speed2 + endurance2 + r.Next(1, 8);
int score3 = speed3 + endurance3 + r.Next(1, 8);
totalScore1 += score1;
totalScore2 += score2;
totalScore3 += score3;
if (score1 > score2 && score1 > score3) //open if
Console.WriteLine(name1 + " takes the lead in lap " + i + "!");
else if (score2 > score1 && score2 > score3)
{
Console.WriteLine(name2 + " takes the lead in lap " + i + "!");
}
else if (score3 > score2 && score3 > score1)
{
Console.WriteLine(name3 + " takes the lead in lap " + i + "!");
} //close if
} // close for
} //close if
else
Console.WriteLine("Okay, take your time.");
if(totalScore1> totalScore2 && totalScore1 > totalScore3 && choice =="Buck")
{
Console.WriteLine("Buckl won the race");
}
} //close while
Console.WriteLine("Aw, too bad. Thanks for joining us!");
} //close main method
}
}
Instead of solving your exact issue, I'd like to show you the power of collections (arrays and Dictionary). They allow you not to manually type every single condition for a single horse (imagine if you had 15 horses)
Since you're a novice, you probably will have hard time understanding this code, but watch and learn!
using System;
using System.Collections.Generic;
struct Horse
{
public string name;
public int endurance;
public int speed;
};
class Program {
public static void Main(string[] args)
{
var horseByName = new Dictionary<string, Horse>
{
{"Buck", new Horse{ name = "Buck", endurance = 6, speed = 4 } },
{"Daisy", new Horse{ name = "Daisy", endurance = 6, speed = 4 } },
{"Leo", new Horse{ name = "Leo", endurance = 7, speed = 3 } },
{"Maya", new Horse{ name = "Maya", endurance = 5, speed = 4 } },
{"Richard", new Horse{ name = "Richard", endurance = 5, speed = 4 } },
};
int balance = 100;
int numberOfHorses = horseByName.Count;
Console.WriteLine("Welcome to the racetrack!");
Console.WriteLine("Today's races will include 10 laps for reach race. There will be 3 races today.");
Console.WriteLine("You have $100 you can choose to bet on one of our 3 horses.");
Console.WriteLine("1. Bet on a horse.");
Console.WriteLine("2. Quit the game.");
string input = Console.ReadLine();
while (input == "1")
{
Console.WriteLine("Would you like to bet on:");
int horseNumber = 1;
foreach (var horse in horseByName.Values)
{
Console.WriteLine($"{horseNumber}. {horse.name}\nEndurance: {horse.endurance}\nSpeed: {horse.speed}");
++horseNumber;
}
string choice = Console.ReadLine();
while (!horseByName.ContainsKey(choice))
{
Console.WriteLine("We don't have such horse, try again:");
choice = Console.ReadLine();
}
Console.WriteLine($"You have chosen {choice}.");
Console.WriteLine($"How much would you like to bet? Your current balance is ${balance}.");
int bet = int.Parse(Console.ReadLine());
Console.WriteLine($"You are betting ${bet} on {choice}. Type \'start\' to start the race.");
string race = Console.ReadLine();
if (race == "start")
{
Console.WriteLine("Let the races begin!");
int[] scores = new int[numberOfHorses];
int maxScorePerLap = 0;
string maxScoredHorseName = "";
for (int lap = 1; lap < 11; lap++)
{
System.Random r = new System.Random();
int horseId = 0;
foreach (var horse in horseByName.Values)
{
scores[horseId] = horse.speed + horse.endurance + r.Next(1, 8);
if (scores[horseId] > maxScorePerLap)
{
maxScorePerLap = scores[horseId];
maxScoredHorseName = horse.name;
}
++horseId;
}
Console.WriteLine($"{maxScoredHorseName} takes the lead in lap {lap}!");
}
if (maxScoredHorseName == choice)
{
Console.WriteLine($"Hurray! {choice} won!");
balance += bet;
}
else
{
Console.WriteLine($"Unfortunately {maxScoredHorseName} won, but you had bet on {choice}...");
balance -= bet;
}
}
else
{
Console.WriteLine("Okay, take your time.");
}
}
Console.WriteLine("Aw, too bad. Thanks for joining us!");
}
}
So, this console app just prints if a number is prime or not, works great for almost every number, but when the assignment is asked to time test the function with two hardcoded numbers (7389274937501454911 and 9389274937501454911) these numbers will not print out anything BUT +1 or -1 to both numbers WILL print out.
using System;
namespace IsPrime
{
class MainClass
{
public static void Main (string[] args)
{
string isPlaying = "y";
bool isPrime;
while(isPlaying == "y")
{
var timer = System.Diagnostics.Stopwatch.StartNew ();
isPrime = isPrimeNum(9389274937501454911);
if (isPrime)
{
Console.WriteLine(9389274937501454911 + " is Prime");
}
else
Console.WriteLine(9389274937501454911 + " is not prime");
isPrime = isPrimeNum(7389274937501454911);
if (isPrime)
{
Console.WriteLine(7389274937501454911 + " is Prime");
}
else
Console.WriteLine(7389274937501454911 + " is not prime");
timer.Stop ();
var time = timer.ElapsedMilliseconds;
Console.WriteLine("Elasped Time: " + time + "\n");
Console.WriteLine("Do you want to play again?: y / n");
isPlaying = Console.ReadLine ();
}
}
static bool isPrimeNum(ulong n)
{
if (n == 1 || n == 2)
return true;
if (n % 2 == 0)
return false;
for(ulong i = 3; i < n; i = i + 2)
{
if (n % i == 0)
return false;
}
return true;
}
}
}
I have reformed your code, try now
using System;
namespace IsPrime
{
class MainClass
{
public static void Main (string[] args)
{
string isPlaying = "y";
bool isPrime;
while(isPlaying == "y")
{
var timer = System.Diagnostics.Stopwatch.StartNew ();
isPrime = IsPrime(9389274937501454911);
if (isPrime)
{
Console.WriteLine(9389274937501454911 + " is Prime");
}
else
Console.WriteLine(9389274937501454911 + " is not prime");
isPrime = IsPrime(7389274937501454911);
if (isPrime)
{
Console.WriteLine(7389274937501454911 + " is Prime");
}
else
Console.WriteLine(7389274937501454911 + " is not prime");
timer.Stop ();
var time = timer.ElapsedMilliseconds;
Console.WriteLine("Elasped Time: " + time + "\n");
Console.WriteLine("Do you want to play again?: y / n");
isPlaying = Console.ReadLine ();
}
}
public static bool IsPrime(ulong number)
{
if (number == 1) return false;
if (number == 2) return true;
if (number % 2 == 0) return false;
//This returns the whole number greater than or equal to the specified number, and in this case
//In this case, I take the square root, obvious to divide in half, so the variable i increases twice, since I'm working with the biggest number and divided in half
var boundary = (ulong)Math.Floor(Math.Sqrt(number));
for (ulong i = 3; i <= boundary; i += 2)
{
if (number % i == 0) return false;
}
return true;
}
}
}
I'm writing a small loop in C# that I want to stay open until the user specifies.
public void ScoreCalc()
{
string goon = " ";
int counter = 1;
int score = 0;
while (goon == " ")
{
Console.WriteLine("Enter a score");
score += int.Parse(Console.ReadLine());
Console.WriteLine(score + " " + counter);
counter++;
}
}
I know this code is not correct.
One way would be to set goon to something other than " " if anything other than an integer is entered by the user.
The easiest way to check if an integer has been entered is by using the Int32.TryParse method.
public void ScoreCalc()
{
string goon = " ";
int counter = 1;
int score = 0;
int userInput = 0;
bool isInt = true;
while (goon == " ")
{
Console.WriteLine("Enter a score");
isInt = Int32.TryParse(Console.ReadLine(), out userInput);
if(isInt)
{
score += userInput;
Console.WriteLine(score + " " + counter);
counter++;
}
else
{
goon = "exit";
}
}
}
public void ScoreCalc()
{
int counter = 1;
int score = 0;
String input;
while (true)
{
Console.WriteLine("Enter a score");
input=Console.ReadLine();
if(input != "end"){
score += int.Parse(input);
Console.WriteLine(score + " " + counter);
counter++;
}else{
break;
}
}
}
I've updated your method assuming "quit" text as an exit signal from the user to break the while loop. Hope this helps!
public void ScoreCalc()
{
string goon = " ";
int counter = 1;
int score = 0;
var userInput = string.Empty;
var inputNumber = 0;
const string exitValue = "quit";
while (goon == " ")
{
Console.WriteLine("Enter a score or type quit to exit.");
userInput = Console.ReadLine();
if (userInput.ToLower() == exitValue)
{
break;
}
score += int.TryParse(userInput, out inputNumber) ? inputNumber : 0;
Console.WriteLine(score + " " + counter);
counter++;
}
}
{
static int[] location = { 0, 0 };
static int player = 0;
static void runGame()
{
int start = Convert.ToInt32(Console.ReadLine());
if (start == 1)
{
location1();
}
else if (start == 2)
{
location2();
}
else if (start == 3)
{
location3();
}
else if (start == 4)
{
location4();
}
}
static void swapPlayer()
{
if (player == 1)
{
player = 0;
}
else
{
player = 1;
}
}
static void location1()
{
Console.WriteLine(" Player " + (player + 1) + " , you are in the kitchen you can go to either \n1: Living room \n2: Bathroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1) {
location[player] = 2;
start = 2;
swapPlayer();
location2();
}
else if (input == 2) {
location[player] = 3;
start = 3;
swapPlayer();
location3();
}
}
static void location2()
{
Console.WriteLine(" Player " + (player + 1) + " you are in the living room you can go to either \n1: Kitchen\n2: Bedroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1) {
location[player] = 1;
start = 1;
swapPlayer();
location1();
}
else if (input == 2) {
location[player] = 4;
start = 4;
swapPlayer();
location4();
}
}
static void location3()
{
Console.WriteLine(" Player " + (player + 1) + " you are in the bathroom you can go to either \n1: Kitchen \n2: Bedroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1)
{
location[player] = 1;
start = 1;
swapPlayer();
location1();
}
else if (input == 2)
{
location[player] = 4;
start = 4;
swapPlayer();
location4();
}
}
static void location4() {
Console.WriteLine(" Player " + (player + 1) + ", you are in the kitchen you can go to either \n1: Living room \n2: Bathroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1)
{
location[player] = 1;
start = 1;
swapPlayer();
location2();
}
else if (input == 2)
{
location[player] = 4;
start = 4;
swapPlayer();
location3();
}
}
static void Main(string[] args)
{
Console.WriteLine("welcome , find the ghost and navigate through the house");
Console.Write("You are in the main hall way you can go to any of these rooms");
Console.Write(" kitchen, living room, bath room , bedroom");
Console.WriteLine("choose a room number 1 , 4 from the list ");
int start = Convert.ToInt32(Console.ReadLine());
bool play = true;
while (play== true)
{
runGame();
}
}
}
Here is the code behind a simple 2 player text adventure I am making , I was wondering where I have used the variable start in the runGame procedure how can i access that outside of the procedure , or is that not possible in which case do you have another solution on how I can get around this.
You can't, and that's the point of local variables: the world outside shouldn't care about their value (or even their existence)
If you want to access the vatiable from multiple methods, you'll have to elevate it to a (in this case static) class member:
static int[] location = { 0, 0 };
static int player = 0;
static int start;