I'm building a webshop mockup in a console app (school project) where the user registers with a number of readlines. For example; the user is prompted to input their desired age, but if the age is lower than 15 or higher than 100 or if the input isn't parseable as an int, the user gets a .Write("Error, try again: ").
My goal is to remain on the same line until the user inputs an age that is valid.
Error, try again: _______
right now it just keeps posting the same error message making the whole thing unreadable.
public static void ClearLine()
{
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop - (Console.WindowWidth >= Console.BufferWidth ? 1 : 0));
}
With this code I am able to remain on the same line, but the error message disappears & the text i just wrote still remains and the console simply writes over it, it's better for sure but I'd love it if I could just clear the text and keep inputting until it's valid
if (!int.TryParse(Console.ReadLine(), out number) ||
number > maxValue || number < minValue)
{
Console.Write("Wrong input, try again: ");
Thread.Sleep(800);
ClearLine();
}
and this is the code that tries the input
It seems you're writing a Console app, not a Web app (webshop)
Your teacher must be over 60 to put this requirement. In the old days, we did it like this on a VT-330 terminal. Input only backspace, ENTER and numbers..
string squestion = "What's your age ?";
int lenquestion = squestion.Length + 1;
while (true) {
string sanswer = "";
Console.Write(squestion + " ___");
Console.SetCursorPosition(lenquestion, Console.CursorTop);
while (true) {
var c = Console.ReadKey();
if (c.Key == ConsoleKey.Enter) break;
if (c.Key != ConsoleKey.Backspace) sanswer += c.KeyChar;
else if (sanswer != "") sanswer = sanswer.Remove(sanswer.Length - 1);
Console.SetCursorPosition(lenquestion, Console.CursorTop);
Console.Write(sanswer + '_');
Console.SetCursorPosition(lenquestion+sanswer.Length, Console.CursorTop);
}
Console.Write(squestion+" "+sanswer);
if (int.TryParse(sanswer, out int age)) {
if (age < 60 || age > 120) {
Console.WriteLine("\t ... you lied ! try again.."); // same line
continue;
}
}
else {
Console.WriteLine("\t ... invalid input ! try again.."); // same line
continue;
}
Console.WriteLine("\t ... thank you for being honest !");
Console.WriteLine("\nPress <enter> to leave..");
Console.ReadLine();
break;
}
Related
Is there a way to ignore a line/block of code if the condition is met?
I'm doing a C# .NET tutorial, and the application is a number guessing game.
I added a hint option if the user enters a wrong number (else if part):
// While guess is not correct
while (guess != correctNumber)
{
//Get users input
string input = Console.ReadLine();
// Make sure it's a number
if (!int.TryParse(input, out guess))
{
// Print error message
PrintColorMessage(ConsoleColor.Red, "Please use an actual number");
// Keep going
continue;
}
// Cast to int and put in guess
guess = Int32.Parse(input);
// Check if guess is close to correct number
if(guess == correctNumber + 2 || guess == correctNumber - 2)
{
// Tell the user that he is close
PrintColorMessage(ConsoleColor.DarkCyan, "You are close!!");
}
// Match guess to correct number
else if (guess != correctNumber)
{
// Print error message
PrintColorMessage(ConsoleColor.Red, "Wrong number, please try again");
AskForAHint(correctNumber);
}
}
// Print success message
PrintColorMessage(ConsoleColor.Yellow, "You are CORRECT!");
Basically I am asking a user if he wants a hint, and if he writes Y, the hint will be displayed. However, is there an option to display this question only once since this if statement is included in a while loop?
It would be annoying if "Do you want a hint?" question keeps displaying even if the user says Y.
My AskForAHint function:
static void AskForAHint(int num)
{
// Ask user if he wants a hint
Console.WriteLine("Do you want a hint? [Y/N]");
// Take his answer
string ans = Console.ReadLine().ToUpper();
// If the user wants a hint
if (ans == "Y")
{
// First hint number
int beginning = (num - num % 10);
// Second hint number
int finish = beginning + 10;
// Give user a hint
Console.WriteLine("The correct number is somewhere betweer {0} and {1}", beginning, finish);
}
else if (ans == "N")
{
return;
}
}
Thanks
Another way to do it would be to make the number of hints configurable (allowing the caller to specify how many hints they want to let the user ask for), and then keep track of the number of hints given in the method itself.
This would require a slight change to the AskForAHint method, however, since we don't know if the user answered "Y" or "N" to the hint question. Since AskForHint has no return value, we could have it return a bool that indicates how the user responded to the question:
static bool AskForAHint(int num)
{
var answer = GetUserInput("Do you want a hint? [Y/N]: ", ConsoleColor.Yellow);
if (!answer.StartsWith("Y", StringComparison.OrdinalIgnoreCase))
{
return false;
}
var beginning = num - num % 10;
var finish = beginning + 10;
Console.WriteLine($"The correct number is somewhere between {beginning} and {finish}");
return true;
}
Now we can keep track of how many hints the user has received by incrementing a counter in our "Game" method:
// Only ask for a hint if they have any hints (and guesses) remaining
if (hintCount < maxHints && guessCount < maxGuesses)
{
// If they asked for a hint, increase the hint count
if (AskForAHint(correctNumber)) hintCount++;
// If they didn't want a hint, max out hint count so we don't ask again
else hintCount = maxHints;
}
To test out the sample code above, I used this method below, which also allows us to configure how many total guesses the user has, what the min and max values of the range should be, and if they should be given a "directional hint", like "too high!" or "too low!":
private static readonly Random Random = new Random();
private static void PlayGuessingGame(int maxHints = 1, int maxGuesses = 10,
int rangeMin = 1, int rangeMax = 100, bool giveDirectionalHint = true)
{
if (rangeMax < rangeMin) rangeMax = rangeMin;
var correctNumber = Random.Next(rangeMin, rangeMax + 1);
var guessCount = 0;
var hintCount = 0;
WriteMessage("Welcome to the guessing game!", ConsoleColor.White);
WriteMessage("-----------------------------\n", ConsoleColor.White);
WriteMessage($"I'm thinking of a number from {rangeMin} to {rangeMax}. ", ConsoleColor.Green);
WriteMessage("Let's see how many guesses it takes you to guess it!\n", ConsoleColor.Green);
do
{
WriteMessage($"(You have {maxGuesses - guessCount} guesses left)");
var input = GetUserInput("Enter the number I'm thinking of: ", ConsoleColor.White);
int guess;
if (!int.TryParse(input, out guess))
{
WriteMessage("Please enter a whole number", ConsoleColor.Red);
continue;
}
// Only increment guesses if they entered an actual number
guessCount++;
if (guess == correctNumber) break;
if (Math.Abs(guess - correctNumber) == 2)
{
WriteMessage("You are close!!", ConsoleColor.DarkCyan);
}
if (giveDirectionalHint)
{
WriteMessage("Wrong number - too " + (guess < correctNumber ? "low!" : "high!"),
ConsoleColor.Red);
}
else
{
WriteMessage("Wrong number, please try again", ConsoleColor.Red);
}
// Only ask for a hint if they have any hints (and guesses) remaining
if (hintCount < maxHints && guessCount < maxGuesses)
{
// If they asked for a hint, increase the hint count
if (AskForAHint(correctNumber)) hintCount++;
// If they didn't want a hint, max out hint count so we don't ask again
else hintCount = maxHints;
}
} while (guessCount < maxGuesses);
WriteMessage("You are CORRECT!", ConsoleColor.Yellow);
GetKeyFromUser("\nDone! Press any key to exit...");
}
This uses the helper functions:
public static void WriteMessage(string message, ConsoleColor color = ConsoleColor.Gray)
{
Console.ForegroundColor = color;
Console.WriteLine(message);
Console.ResetColor();
}
private static string GetUserInput(string prompt, ConsoleColor color = ConsoleColor.Gray)
{
Console.ForegroundColor = color;
Console.Write(prompt);
Console.ResetColor();
return Console.ReadLine();
}
Output
You can see in the output below, I was only given a single hint. However that, combined with the directional hints, made the game easy to win:
I think you can do an "if" with a counter.
Try It
Int cont = 0; //global
// While guess is not correct
while (guess != correctNumber)
{
//Get users input
string input = Console.ReadLine();
// Make sure it's a number
if (!int.TryParse(input, out guess))
{
// Print error message
PrintColorMessage(ConsoleColor.Red, "Please use an actual number");
// Keep going
continue;
}
// Cast to int and put in guess
guess = Int32.Parse(input);
// Check if guess is close to correct number
if(guess == correctNumber + 2 || guess == correctNumber - 2)
{
// Tell the user that he is close
PrintColorMessage(ConsoleColor.DarkCyan, "You are close!!");
}
// Match guess to correct number
else if (guess != correctNumber)
{
// Print error message
PrintColorMessage(ConsoleColor.Red, "Wrong number, please try again");
if(cont == 0){
AskForAHint(correctNumber);
}
}
}
// Print success message
PrintColorMessage(ConsoleColor.Yellow, "You are CORRECT!");
And in the function add
static void AskForAHint(int num)
{
// Ask user if he wants a hint
Console.WriteLine("Do you want a hint? [Y/N]");
// Take his answer
string ans = Console.ReadLine().ToUpper();
// If the user wants a hint
if (ans == "Y")
{
cont = 1;
// First hint number
int beginning = (num - num % 10);
// Second hint number
int finish = beginning + 10;
// Give user a hint
Console.WriteLine("The correct number is somewhere betweer {0} and {1}", beginning, finish);
}
else if (ans == "N")
{
return;
}
}
Use a Member Variable Boolean, its similar to how you can avoid recursive calls.
private bool alreadyHinted = false;
static void AskForAHint(int num)
{
if (alreadyHinted) return;
alreadyHinted = true;
At some point you will need to set alreadyHinted back to false;
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to get this random number guessing game working. The program runs, but it doesn't give the "you won" message when you enter the correct number, and the hint feature does not give the feed back it is supposed to. Any help appreciated.
using System;
namespace randomNumberGame
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
var val = r.Next(1, 100);
var guess = 0;
bool correct = false;
var attemptsLeft = 5;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
while (!correct && attemptsLeft >= 1)
{
Console.Write("You have " + attemptsLeft + " lives left. Please enter your Guess: ");
string input = Console.ReadLine();
var message = "";
var difference = val - guess;
if (!int.TryParse(input, out guess))
{
Console.WriteLine("That's not a number.");
continue;
}
if (difference == 0)
{
Console.WriteLine("You have won");
correct = true;
}
else
{
if (Math.Abs(difference) >= 50)
{
message = Math.Sign(difference) == -1 ? "Very High" : "Very Low";
}
else if (Math.Abs(difference) < 50 && Math.Abs(difference) >= 20)
{
message = Math.Sign(difference) == -1 ? "High" : "Low";
}
else if (Math.Abs(difference) < 20 && Math.Abs(difference) >= 10)
{
message = Math.Sign(difference) == -1 ? "Moderatley High" : "Moderately Low";
}
else if (Math.Abs(difference) < 10)
{
message = Math.Sign(difference) == -1 ? "Somewhat High" : "Somewhat Low";
}
else Console.WriteLine("???");
}
attemptsLeft--;
}
}
}
}
"it doesn't give the you won message when you enter the correct number"
Actually, it does! But then the program exits so quickly that you never see it. To solve this, add a line that waits for the user to press a key at the end of your Main method, so you can see the final result:
// Add this as the last line of the main method:
Console.ReadKey();
"the hint feature does not give the feed back it is supposed too"
This is because you never output the hint message! At the end of your while loop, add a line to do so:
// Add this as the last line of the while loop:
Console.WriteLine(message);
These things can be found easily if you simply set a breakpoint in your code (in Vistal Studio, click the left margin next to one of the lines and a red dot will appear (or press F9)). Then you can step through the code using F10 and you can watch the values of local variables change and see what is happening step-by-step.
Another way to help avoid problems (and to narrow down where they occur) is to take out chunks of code that does something specific and put it in a method. This will make it easier to debug in the long run.
For example, we can write methods that take in a string to display to the user as a prompt for input, and return a strongly-typed value based on their entry. We can also have these methods take in an optional validation method that can be used to validate that the input they entered falls within a valid range (like a number from 1 to 100, or a name that's not longer than 25 characters):
public static string GetStringFromUser(string prompt,
Func<string, bool> validator = null)
{
string result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
result = Console.ReadLine();
} while (!(validator?.Invoke(result) ?? true));
return result;
}
public static int GetIntFromUser(string prompt,
Func<int, bool> validator = null)
{
int result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
} while (!int.TryParse(Console.ReadLine(), out result) ||
!(validator?.Invoke(result) ?? true));
return result;
}
private static void ClearSpecificLineAndWrite(int cursorTop,
string message)
{
Console.SetCursorPosition(0, cursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, cursorTop);
Console.Write(message);
}
We can also write a helper method to get our "difference string", which could take in the guess, the number, and the min and max values, then calculate a percentage of how close they were and then return the appropriate string:
public static string GetDifferenceString(int guess, int number,
int minVal, int maxVal)
{
var percentAway =
Math.Abs(guess - number) / (double)(maxVal - minVal) * 100;
var direction = guess - number > 0 ? "High" : "Low";
if (percentAway < 10) return $"Very close, but {direction}";
if (percentAway < 20) return $"Just a little {direction}";
if (percentAway < 30) return $"Somewhat {direction}";
if (percentAway < 40) return $"Moderately {direction}";
if (percentAway < 50) return $"{direction}";
return $"Very {direction}";
}
This simplifies our main code by removing the loops and checking results from there, and lets us focus on our main tasks:
static void Main(string[] args)
{
var randomNumber = new Random().Next(1, 101);
var maxAttempts = 5;
var guess = 0;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
Console.WriteLine($"You have {maxAttempts - attempt} " +
$"out of {maxAttempts} attempts remaining.");
guess = GetIntFromUser("Please enter your guess (1 - 100): ",
i => i > 0 && i < 101);
if (guess == randomNumber)
{
Console.WriteLine($"You have won in {attempt + 1} tries!");
break;
}
Console.WriteLine(GetDifferenceString(guess, randomNumber, 1, 100));
}
if (guess != randomNumber)
{
Console.WriteLine("Sorry, you lose! The number was: " +
$"{randomNumber}");
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
I have a C# console program that asks the user for a certain word by showing a input prompt. The input is then processed using an switch statement. If the word is correct, the program continues. But if the input doesn't match, the program says "Error: invalid input" and then goes back to the input prompt. The tricky part is that I want the program to clear the input that the user just typed before pressing Enter and prompt the user again, without making another separate prompt below the first one.
Is there a library of some kind in C# that does something like that, or do I have to make a library for it?
One way to do this is to use a combination of Console.SetCursorPosition and Console.Write to set the cursor to the beginning of their response, write enough whitespace to "erase" their reaponse, and then set the cursor back to the beginning again.
For example:
static string GetUserInput(string prompt, List<string> validResponses)
{
Console.Write(prompt);
// Capture the cursor position just after the prompt
var inputCursorLeft = Console.CursorLeft;
var inputCursorTop = Console.CursorTop;
// Now get user input
string input = Console.ReadLine();
while (validResponses != null &&
validResponses.Any() &&
!validResponses.Contains(input, StringComparer.OrdinalIgnoreCase))
{
Console.ForegroundColor = ConsoleColor.Red;
// PadRight ensures that this line extends the width
// of the console window so it erases itself each time
Console.Write($"Error! '{input}' is not a valid response".PadRight(Console.WindowWidth));
Console.ResetColor();
// Set cursor position to just after the promt again, write
// a blank line, and reset the cursor one more time
Console.SetCursorPosition(inputCursorLeft, inputCursorTop);
Console.Write(new string(' ', input.Length));
Console.SetCursorPosition(inputCursorLeft, inputCursorTop);
input = Console.ReadLine();
}
// Erase the last error message (if there was one)
Console.Write(new string(' ', Console.WindowWidth));
return input;
}
In use this might look like:
static void Main(string[] args)
{
var validResponses = new List<string> {"Yes", "No"};
var userInput = GetUserInput("Do you like me? ", validResponses);
if (userInput.Equals("Yes", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("I like you too!");
}
else
{
Console.WriteLine("And all along I thought you had good taste.");
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
Here's a sample run of the program. I had to include several screenshots since the response (and then the error message) are cleared on each iteration:
Try this ...
static void Main(string[] args)
{
CheckWord();
Console.ReadKey();
}
private static void CheckWord()
{
while (true)
{
string errorMessage = "Error: invalid input ... enter a valid entry";
string word = Console.ReadLine();
if (word != "word")
{
Console.SetCursorPosition(word.Length +1 , (Console.CursorTop) - 1);
Console.Write(errorMessage);
Console.ReadKey();
Console.SetCursorPosition(0, Console.CursorTop);
for (int i = 0; i <= word.Length + errorMessage.Length +1 ; i++)
{
Console.Write(" ");
}
Console.SetCursorPosition(0, Console.CursorTop);
}
else
{
break;
}
}
}
I am fairly new to C# and currently building a simple ATM app. I am attempting to write code to return the user to the main menu according to his/her entry of the letter M. The break, continue, goto or return keywords do not seem to work in my scenario; perhaps I used them incorrectly. The statement directly below is where I would like to jump to.
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
I would like to jump from the line JUMP (below) within the else if statement nested within the switch statement into the section of code above. How can I achieve this? any help is appreciated...thanks!
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
Using a jump statement usually indicates the flow of logic is jumbled. I try to avoid any kind of jumps if necessary. The code below prints out a main menu and if the user types “x” the program will quit. If the user selects one of the other options, a message is simply printed out indicating what the user selected. After the user presses any key, the console clears and the main menu is re-displayed.
In the main menu, if the user does not type one of the selections, then the selection is ignored, the console is cleared, and the menu is reprinted. No error is displayed indicating invalid selections.
This does not require the user to type “m” to go back to the main menu. After a selection is made for Deposit/withdraw/… after the method is finished the code will automatically return to the main menu.
I am guessing this may be what you are looking for. Hope this helps.
static void Main(string[] args) {
string userInput = "";
while ((userInput = GetMainSelection()) != "x") {
switch (userInput) {
case "c1":
Console.WriteLine("C1 Deposit Checking method");
break;
case "c2":
Console.WriteLine("C2 Deposit Savings method");
break;
case "b1":
Console.WriteLine("B1 View Balance Checking method");
break;
case "b2":
Console.WriteLine("B2 View Balance Savings method");
break;
case "w1":
Console.WriteLine("W1 Withdraw Checking method");
break;
case "w2":
Console.WriteLine("W2 withdraw Savings method");
break;
}
Console.WriteLine("Press Any Key to continue"); // <-- show what method was just used
Console.ReadKey();
Console.Clear();
}
Console.Write("Press any key to exit the program");
Console.ReadKey();
}
private static string GetMainSelection() {
string userInput = "";
while (true) {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving. (X) to EXit");
userInput = Console.ReadLine().ToLower();
if (userInput == "b1" || userInput == "b2" || userInput == "c1" || userInput == "c2" || userInput == "w1" || userInput == "w2" || userInput == "x") {
return userInput;
}
else {
Console.Clear();
}
}
}
Put the JUMP code in a function and return.
public void MainMenu() {
// Show the main menu
}
public void Response(string response) {
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
MainMenu();
return;
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
}
}
Similar to the already given answer, I suggest breaking this out. Here's an example:
The Main method:
static void Main(string[] args) {
string input = null;
do {
input = Console.ReadLine();
ParseInput(input);
} while (input != "X");
}
ParseInput:
static void ParseInput(string input) {
switch (input) {
case "X": //from Main(), this will close the app
return;
case "M":
MainMenu();
break;
case "C1":
ShowAccount("C1"); //move your deposit/withdraw logic into a method and call with the selected account
return;
//other accounts
default:
break; //error message?
}
}
and MainMenu:
static void MainMenu() {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
}
This should let you read the input in a loop and the ParseInput function can handle your individual cases. You may also want to call MainMenu() at the start, so it shows from the beginning.
It works like this:
Get input from the user
Pass the input to ParseInput() which decides where to go next.
Any functions hit in ParseInput() will execute, writing to the console or asking for further input
Once that function returns, while (input != "X") evaluates. If input != "X", goto 1, else exit.
I suggest you use goto C# reference.
static void Main()
{
int x = 200, y = 4;
int count = 0;
string[,] array = new string[x, y];
// Initialize the array:
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
array[i, j] = (++count).ToString();
// Read input:
Console.Write("Enter the number to search for: ");
// Input a string:
string myNumber = Console.ReadLine();
// Search:
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
if (array[i, j].Equals(myNumber))
{
goto Found;
}
}
}
Console.WriteLine("The number {0} was not found.", myNumber);
goto Finish;
Found:
Console.WriteLine("The number {0} is found.", myNumber);
Finish:
Console.WriteLine("End of search.");
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Output for the Input 44 would be:
Enter the number to search for: 44
The number 44 is found.
End of search.
See here for the MSDN reference.
I'm doing my first console application at school which is a Cheese Racer Game. Sixteen pieces of cheese are distributed on the board by up to 4 players. Two pieces of cheese cannot be placed on this same square, which is decided by another method which returns a bool. Here is what I have so far.
do
{
for (int i = 0; i < NoOfPlayers; i++)
{
string YourTurnCheese = "Your turn, " + players[i].Name + "!";
Console.SetCursorPosition((Console.WindowWidth - YourTurnCheese.Length) / 2, Console.CursorTop);
Console.WriteLine(YourTurnCheese);
do
{
string XCoordinate = "X Coordinate: ";
Console.SetCursorPosition((Console.WindowWidth - XCoordinate.Length) / 2, Console.CursorTop);
Console.Write(XCoordinate);
int.TryParse(Console.ReadLine(), out CheeseX);
if (CheeseX > 7 || CheeseX < 0)
Console.WriteLine("Please enter a number from 0 to 7");
else
break;
} while (true);
do
{
string YCoordinate = "Y Coordinate: ";
Console.SetCursorPosition((Console.WindowWidth - YCoordinate.Length) / 2, Console.CursorTop);
Console.Write(YCoordinate);
int.TryParse(Console.ReadLine(), out CheeseY);
if (CheeseY > 7 || CheeseY < 0)
Console.WriteLine("Please enter a number from 0 to 7");
else
break;
} while (true);
if (!TryToPlaceCheese(CheeseX, CheeseY))
{
string CheeseisHere = "There is already a piece of cheese at this location.";
Console.SetCursorPosition((Console.WindowWidth - CheeseisHere.Length) / 2, Console.CursorTop);
Console.WriteLine(CheeseisHere);
}
else
{
Board[CheeseX, CheeseY] = SquareState.gotCheese;
TotalCheesePlaced = (TotalCheesePlaced + 1);
}
}
} while (TotalCheesePlaced < 16);
I'm not sure how to make it reject empty input into the console. Also, when there is already a cheese piece on the location given, it states that, but moves onto the next player instead of looping back. Can I get some help with fixing that code please? I'm still pretty new to all of this so please be gentle :)
Your problem is here:
int.TryParse(Console.ReadLine(), out CheeseX);
First, split this as follows:
string input = Console.ReadLine();
int.TryParse(input, out CheeseX);
Now, you are parsing the input but not doing anything when the input is invalid. The TryParse method returns true if it succesfully converted the input to an integer, and false otherwise. So you could do something like this:
if (!int.TryParse(input, out CheeseX))
{
Console.WriteLine("invalid input, try again");
break;
}
This way, it does not move onto the next person when the field is occupied.
do
{
for (int i = 0; i < NoOfPlayers; i++)
{
do
{
...
do
{
...
if (CheeseX > 7 || CheeseX < 0)
Console.WriteLine("Please enter a number from 0 to 7");
else
break;
} while (true);
do
{
...
if (CheeseY > 7 || CheeseY < 0)
Console.WriteLine("Please enter a number from 0 to 7");
else
break;
} while (true);
if (!TryToPlaceCheese(CheeseX, CheeseY))
{
string CheeseisHere = "There is already a piece of cheese at this location.";
Console.SetCursorPosition((Console.WindowWidth - CheeseisHere.Length) / 2, Console.CursorTop);
Console.WriteLine(CheeseisHere);
}
else
{
Board[CheeseX, CheeseY] = SquareState.gotCheese;
TotalCheesePlaced = (TotalCheesePlaced + 1);
}
} while (!TryToPlaceCheese(CheeseX, CheeseY));
}
} while (TotalCheesePlaced < 16);