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);
Related
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;
}
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'm creating a program for a college assignment and the task is to create a program that basically creates random times table questions. I have done that, but need to error check the input to only accept integer inputs between 1-100. I can not find anything online only for like java or for text box using OOP.
Here is my code:
static void help()
{
Console.WriteLine("This program is to help children learn how to multiply");
Console.WriteLine("The program will create times table questions from 1-10");
Console.WriteLine("The user will be given 10 random questions to complete");
Console.WriteLine("The user will get a score out of 10 at the end");
Console.WriteLine("If the user gets the answer wrong, the correct answer will be displayed");
Console.WriteLine("");
Console.ReadLine();
Console.Clear();
}
static void Main(string[] args)
{
int Random1 = 0;
int Random2 = 0;
int Answer;
int Count = 0;
int Score = 0;
int input = 0;
String choice;
Console.WriteLine("To begin the Maths test please hit any key");
Console.WriteLine("If you need any help, just, type help");
choice = Console.ReadLine();
if (choice == "help")
{
help();
}
while (Count != 10)
{
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
input = int.Parse(Console.ReadLine());
Answer = Random1 * Random2;
if (Answer == input)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Correct");
Score = Score + 1;
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Thats the wrong answer, the correct is " + Answer);
Console.ResetColor();
}
}
if (Score > 5)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Good job you got more than 5 answers correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
else if (Score < 5)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("");
Console.WriteLine("Try again you got less than 5 correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
}
}
}
Firstly, I suggest you to use TryParse instead of Parse to prevent unexpected errors because of invalid inputs. So, try something like that;
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
//Modified
int input = 0;
while (true)
{
if (!int.TryParse(Console.ReadLine(), out input))
{
Console.WriteLine("Invalid Input. Please enter a valid integer.");
}
else
{
if (input >= 1 && input <= 100)
{
break;
}
Console.WriteLine("Invalid Input. Please enter a integer between 1-100.");
}
}
//Modified
I'd simply use a loop that will keep asking for input until it
matches your requirement:
int MinVal = 1; // No magic numbers! You may consider placing them in a config
int MaxVal = 100; // or as static readonly class members (a bit like "const").
int input = -1;
for(;;) // "empty" for-loop = infinite loop. No problem, we break on condition inside.
{
// attempt getting input from user
bool parseOK = int.TryParse(Console.ReadLine(), out input);
// Exit loop if input is valid.
if( parseOK && input >= MinVal && input <= MaxVal ) break;
Console.WriteLine( "Errormessage telling user what you expect" );
}
You may also consider granting only N trys to get the input right.
A few hints:
do not use "magic numbers". Define constants or put numbers into Properties/Settings. Name them self-explanatory and document why you chose the value they happen to have.
The errormessage should tell the user what an expected valid input is (as opposed to what they typed in) not just that their input was invalid.
Whats about this?
input = int.Parse(Console.ReadLine());
if(input > 1 && input < 100){
// valid
}else{
// invalid
}
I'm having a hard time wrapping my mind around this. Every time the player makes a wrong guess, it should subtract his/her bet from the initial balance.
Since it is in a loop, it always takes the initial balance from the beginning spits out the same balance every time. (obviously)
I've tried assigning different variables and just can't seem to figure it out.
I've omitted the medium and hard difficulty methods as they are of no use right now, until I figure out this one.
My Main() only calls the setDifficulty(). Nothing else.
class Control
{
int selectedNumber = 0;
Random num = new Random();
bool playAgain = true;
int difficulty = 0;
int bet = 0;
int initialBalance = 20;
int runningCredits = 0;
int credits = 0;
public Control()
{ }
//sets game difficulty
public void SetDifficulty()
{
Console.Clear();
Console.WriteLine("Please select level of difficulty between 1 - 100");
difficulty = int.Parse(Console.ReadLine());
if (difficulty >= 1 && difficulty <= 20)
LetsPlayEasy();
else if (difficulty >= 21 && difficulty <= 50)
LetsPlayMedium();
else if (difficulty >= 51 && difficulty <= 100)
LetsPlayHard();
else
{
SetDifficulty();
}
}
//easy level method
public void LetsPlayEasy()
{
//variables
int userGuess;
int numGuesses = 0;
selectedNumber = num.Next(1, 101);
Console.BackgroundColor = ConsoleColor.DarkYellow;
Console.Clear();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Difficulty level = EASY");
Console.WriteLine("\nBeggining credit balance = " + initialBalance);
Console.WriteLine("\nPlease place a bet. You will lose those credits for every incorrect guess!");
bet = int.Parse(Console.ReadLine());
do
{
Console.WriteLine("\nGuess a number between 1 and 100.");
userGuess = Convert.ToInt32(Console.ReadLine());
numGuesses++;
UI output = new UI();
output.CompareNumbers(userGuess, ref selectedNumber, ref playAgain, ref numGuesses);
runningCredits = (initialBalance - bet);
Console.WriteLine("\nYou have " + runningCredits + " credits remaining.");
} while (playAgain == true);
}
class UI
{
Random num = new Random();
int keepGoing;
public UI()
{ }
//compare user's guess to selected number
public void CompareNumbers(int userGuess, ref int selectedNumber, ref bool playAgain, ref int numGuesses)
{
Control difficulty = new Control();
Admin say = new Admin();
if (userGuess > selectedNumber)
{
Console.Beep(600, 300);
Console.WriteLine("\nToo High! Guess Again!");
}
else if (userGuess < selectedNumber)
{
Console.Beep(300, 300);
Console.WriteLine("\nToo Low! Guess Again!");
}
else
{
Console.Beep(350, 300);
Console.Beep(380, 200);
Console.Beep(380, 100);
Console.Beep(500, 1100);
Console.WriteLine("\n\nCongrats! It took you " + numGuesses + " guesses to win.");
numGuesses = 0;
Console.WriteLine("Press 1 to play again or 2 to quit.");
keepGoing = int.Parse(Console.ReadLine());
while (keepGoing != 1 && keepGoing != 2)
{
Console.WriteLine("\n\nPlease type either 1 or 2 only!");
keepGoing = int.Parse(Console.ReadLine());
}
if (keepGoing == 2)
{
playAgain = false;
say.Goodbye();
}
else
{
Console.Clear();
difficulty.SetDifficulty();
}
}
}
}
}
Initialise runningBalance to initialBalance and only use this value for calculations. If you only need initialBalance once, you can also do it by simply switching runningBalance to initialBalance without initializing runningBalance.
Console.WriteLine("\nBeggining credit balance = " + initialBalance);
Console.WriteLine("\nPlease place a bet. You will lose those credits for every incorrect guess!");
bet = int.Parse(Console.ReadLine());
runningBalance = initialBalance
do
{
Console.WriteLine("\nGuess a number between 1 and 100.");
userGuess = Convert.ToInt32(Console.ReadLine());
numGuesses++;
UI output = new UI();
output.CompareNumbers(userGuess, ref selectedNumber, ref playAgain, ref numGuesses);
runningCredits -= bet;
Console.WriteLine("\nYou have " + runningCredits + " credits remaining.");
} while (playAgain == true);
runningCredits = (initialBalance - bet);
You don't change initialBalance or bet in the loop, so every iteration has the same value of runningCredits.
Outside the loop, do this:
runningCredits = initialBalance;
Inside the loop, do this:
runningCredits -= bet;
Note: you don't have any code to check in the loop to see if the user guessed right or wrong (and as such, the user always loses and you always subtract out the bet).
Is there a way to check a lenth of integer variable, and if is to long just trim it.
I hava a field in database that accepts 3 character, lenth is 3.
So is it possible to do like it's done with string variable
example:
cust_ref = cust_ref.Length > 20 ? cust_ref.Substring(0, 19) : cust_ref;
Thanks!
The easiest answer would be:
//The length would be 3 chars.
public int myint = 111;
myint.ToString().Length;
The following worked a treat for me!
public static int IntLength(int i)
{
if (i < 0)
throw new ArgumentOutOfRangeException();
if (i == 0)
return 1;
return (int)Math.Floor(Math.Log10(i)) + 1;
}
Original Source: http://www.java2s.com/Code/CSharp/Data-Types/Getthedigitlengthofanintvalue.htm
You don't have to convert it to a string to make it shorter, that can be done numerically:
if (num > 999) {
num %= 1000;
}
This will cut of digits from the left, if you want to cut them off from the right:
while (num > 999) {
num /= 10;
}
If the value can be negative, also check:
if (num < -99) {
num = -(-num % 100);
}
or:
while (num < -99) {
num = -(-num / 10);
}
cust_ref = cust_ref.ToString().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref;
or simply use
cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));
Use like this
cust_ref= cust_ref.Tostring().Length > 20 ? Convert.ToInt32(cust_ref.ToString().Substring(0, 19)) : cust_ref;
Nont very clear what you're asking for, but as much as I unerstood you're asking for:
int a = 1234567890;
for some reason you want to make it shorter, like
int b = MakeShorter(a);
//b == 1234 (say)
If so, the easiest solution may be, convert it to string, made what you already implemented and reconvert it back to int.
If this is not what you're asking for, please clarify.
The conversion to the string is ugly way to implement it.
It's require a pure math solution
int CutTheNumber(int number, int maxLen)
{
var maxSize = (int)Math.Pow(10, maxlen);
if(maxSize <= Math.Abs(number))
{
number %= maxSize;
}
return number;
}
Checking length
length = cust_ref.ToString().Length;
Remove extra bits
if (length > need)
{
cust_ref =Convert.ToInt32( cust_ref.ToString().Remove(length -(length- need)));
}
for this u will have to do some simple stuffs.
like
cust_ref = Convert.ToInt32(Convert.ToString(cust_ref).Substring(0, 19));
or u can manually store it in any variable and the
You can try this code. use if else statement to check the validation ..
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace avaragescore
{
class Program
{
static void Main(string[] args)
{
float quiz;
float midterm;
float final;
float avrg=0;
Start:
Console.WriteLine("Please enter the Quize Score here");
quiz = float.Parse(Console.ReadLine());
if(quiz > 100)
{
Console.WriteLine("You have entered wrong score please re-enter");
goto Start;
}
Start1:
Console.WriteLine("Please enter the Midterm Score here");
midterm = float.Parse(Console.ReadLine());
if(midterm > 100)
{
Console.WriteLine("You have entered wrong score please re- enter");
goto Start1;
}
Start3:
Console.WriteLine("Please enter the Final Score here");
final = float.Parse(Console.ReadLine());
if(final > 100)
{
Console.WriteLine("You have entered wrong Score Please re-enter");
goto Start3;
}
avrg = (quiz + midterm + final) / 3;
if(avrg >= 90)
{
Console.WriteLine("Your Score is {0} , You got A grade",avrg);
}
else if (avrg >= 70 && avrg < 90)
{
Console.WriteLine("Your Score is {0} , You got B grade", avrg);
}
else if (avrg >= 50 && avrg < 70)
{
Console.WriteLine("Your Score is {0} , You got C grade", avrg);
}
else if (avrg < 50)
{
Console.WriteLine("Yor Score is {0} , You are fail", avrg);
}
else
{
Console.WriteLine("You enter invalid Score");
}
Console.ReadLine();
}
}
}