C# How can I make an exception to allow only numbers? - c#

Here is my Code
Console.WriteLine("Do you want to: 1. play against an Ai or 2. let two Ai´s play aigainst each other?");
Console.WriteLine("Please choose one option!");
int userInput = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n");
if (userInput == 1)
{
// Player
Player player = new Player();
I tried to make an try catch block but then I always got a porblem with userInput in my if statement. I want a try .. catch block to make sure, if the user enters a char or somethingelse (+,~,#,...) they get an error message and can enter something new.

I suggest using loop and if instead of catching exceptions (exceptions have been designed for exceptional situations which are not the case - we should validate user input only):
int userInput = -1;
// Keep on asking user until valid input is provided
while (true) {
Console.WriteLine("Do you want to:");
Console.WriteLine(" 1. play against an Ai or ");
Console.WriteLine(" 2. let two Ai´s play aigainst each other?");
Console.WriteLine("Please choose one option!");
// Trim() - let's be nice and tolerate leading and trailing spaces
string input = Console.ReadLine().Trim();
if (input == "1" || input == "2") {
userInput = int.Parse(input);
break;
}
Console.WriteLine("Sorry, invalid option. Please, try again.");
}

Related

C# Conditions statement

I'm working on a conditional statement and I'm having difficulty getting my small transportation console application to run properly in Windows Studio 2022. After pressing 1 or 2 (Yes or No) my application goes back to my main menu instead of proceeding to the user choosing a route or choosing not to purchase a ticket.
{
Console.WriteLine("Would you like to buy a Ticket?\n");
Console.WriteLine("Please Type 1 for: Yes");
Console.WriteLine("Please Type 2 for: No");
var response = Console.ReadLine();
Console.WriteLine(response);
int num = 1;
if (num == 1)
{
Console.WriteLine("1) For the first route option, please type 1");
Console.WriteLine("2) For the second route option, please type 2");
}
int num2 = 2;
if (num2 == 2)
{
Console.WriteLine("No Ticket Purchased: Have a great day!");
}
else
{
Console.WriteLine("Your answer was not vaild");
}
I'd expect your code to look something like this -- where you check the response value.
{
Console.WriteLine("Would you like to buy a Ticket?\n");
Console.WriteLine("Please Type 1 for: Yes");
Console.WriteLine("Please Type 2 for: No");
var response = Console.ReadLine();
Console.WriteLine(response);
if (response == '1')
{
// do something to let them buy a ticket
}
else
if (response == '2')
{
Console.WriteLine("No Ticket Purchased: Have a great day!");
}
else
{
Console.WriteLine("Your answer was not vaild");
}
}
You are reading the data in the variable called response and never using it.
You are setting the data in the variable num1 with value 1 and num2 with 2, and you are checking them in the if condition.
You can try to create functions to execute within the if-else blocks to give you better readability over the code.
First , the answers that I see in this page is correct.
it seems that you forgot the using of the response.
But I’m having trouble understanding your question.
You declare response as a var and then you decide to use int.
No problem, you can make it if you want.
But if you want to use int , you need to put it in try-catch block in order to avoid get an exception in case user will enter string.
This exception will get when you convert the var to int.
I add some comments to explain the code.
if you have questions - don't hesitate to ask.
goodluck !
private static void BuyTicket(bool retry = true)
{
int selection = 0;
Console.WriteLine("Would you like to buy a Ticket?\n");
Console.WriteLine("Please Type 1 for: Yes");
Console.WriteLine("Please Type 2 for: No");
var response = Console.ReadLine();
//for case user enter a string and not a number, so need to give friendly message of the options available
try
{
selection = int.Parse(response);
}
catch (Exception ex)
{
Console.WriteLine("Please choose '1' or '2' only");
Console.WriteLine(ex.Message);
if (retry == true)
{
//if the user will enter invalid data this time , it will skip and continue
BuyTicket(false);
}
}
if (selection == 1)
{
Console.WriteLine("You choosed to buy a ticket.");
Console.WriteLine("1) For the first route option, please type 1");
Console.WriteLine("2) For the second route option, please type 2");
response = Console.ReadLine();
Console.WriteLine("Thanks for your choice. You choose " + int.Parse(response) + " route option");
}
else if (selection == 2)
{
Console.WriteLine("No Ticket Purchased: Have a great day!");
}
else
{
Console.WriteLine("Your answer was not vaild. Please enter '1' or '2' only");
}
}

How do you use a "char" as a sentinel value in a while loop

My Instructions:
Implement a C# console application/program that makes use of a sentinel controlled while-loop structure to continuously prompt, read and store the test results entered by the user. The user will stop his/her input sequence by entering a ‘x’ character. You also need to make use of a switch selection structure (nested inside of the while loop).
e.g code to be used:
char stop = 'x';
Console.WriteLine("Enter result (x to stop): ");
results = Convert.ToChar(Console.ReadLine());
while(results != stop)
{
Console.WriteLine("Enter result (x to stop): ");
results = Convert.ToChar(Console.ReadLine());
}
When I try to enter the 'x' as is, it does not work
you are using Console.WriteLine, but you should use Console.ReadKey and omit Convert.ToChar instead get the KeyChar property of the returned value.
so
while(results != stop)
{
Console.WriteLine("Enter result (x to stop): ");
results = Console.ReadKey().KeyChar;
}
should work, I didn't test it
You convert into wrong type: not every string can be converted into a single char (say, "xenogg").
However, every char can be represented as a string with a help of ToString():
char stop = 'x';
// Keep looping ...
while (true) {
// ...and asking user for input...
Console.WriteLine("Enter result (x to stop): ");
string results = Console.ReadLine();
// ... until (s)he puts "x"
// put StringComparison.OrdinalIgnoreCase if 'X' is exit as well as 'x'
if (string.Equals(results.Trim(), x.ToString(), StringComparison.Ordinal))
break;
// results is not "x"
//TODO: add relevant code here
}

c# cant run two functions in a loop?

What i want to do is to make it that inside a loop, the computer checks whether the number entered is firstly not a decimal, and at the same time i want to make sure that the number is within the range 1 - 100. My code now works in regards to having the first function about the number not being a decimal, so when i enter a decimal, an error message is displayed that tells the user to keep adding another number until an integer is added, and it then runs to the next part. However it doesn't seem to work when i put in a number outside of the range, the error message doesn't pop up and the conditions just don't seem to work. What i want to know is how do i get these two parts, the decimal and the range checking to work simultaneously. I'm really new to coding so could any explanations be simple so that i could understand. Thank you in advance!
string inputcost;
string inputmoney;
int validcost;
int validmoney;
int changereq;
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
bool result = int.TryParse(inputcost, out validcost);
while (!int.TryParse(inputcost, out validcost))
{
if (result == true )
{
Console.Write("Valid Value");
}
if (result == false)
{
Console.Write("You Cannot Enter Decimals. Please Enter A Valid Integer Value.");
Console.WriteLine();
inputcost = Console.ReadLine();
}
if (validcost < 100 && validcost > 1)
{
Console.Write("valid value");
}
else
{
Console.Write("invalid value.please enter a number between 1 and 100 ");
Console.ReadLine();
}
}
The line
while (!int.TryParse(inputcost, out validcost))
means that you enter the while loop only when the user types something that cannot be converted to an integer. If it is a valid integer the code inside the while loop is never reached and thus, your test on the valid range is never executed
Instead put everything inside the an infinite loop and provide a way to break the program (type x to quit)
while (true)
{
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: (type x to quit)");
inputcost = Console.ReadLine();
// Check if the user wants to stop executing the program
if(inputcost == "x")
break;
// Check if it is a valid integer
bool result = int.TryParse(inputcost, out validcost);
if (!result)
{
Console.WriteLine("You Cannot Enter Decimals (or strings). Please Enter A Valid Integer Value.");
}
else if (validcost > 100 || validcost < 1)
{
Console.WriteLine("invalid value.please enter a number between 1 and 100 ");
}
else
{
Console.WriteLine("Valid value");
// other code block that works with the input number....
}
}
Alternativly use another condition for your loop, something that first checks for an integer and afterwards if it is in range:
while (!int.TryParse(inputcost, out validcost)) || validCost < 1 || validCost > 100)
{
Console.WriteLine("Please enter an integer between 1 and 100");
inputCost = Console.ReadLine();
}
All the code that should be executed when your inout is valid should now gow beyond the loop, not inside it.

I need to develop a Calculator type Program in Console Application in C sharp

I'm new to C sharp Programming and i'm stuck with a program to develop a Calculator like functionality in which it will take the user's input into a int data type called choice and it will read both the operands from user to calculate upon then a switch loop will be executed which on depending on the choice selected perform the desired operation and will give the Output Result.After showing result and breaking the case,the program will ask the user whether to Continue or not and the feedback will be stored on a character variable which will be compared and if selected Y it will redirect the program's execution to the start label.
Below is the Code for the Same:
public static void Main(string[] args)
{
int choice,op1,op2;
char ch;
start:
Console.WriteLine("Enter First Operand");
op1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Second Operand");
op2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your Input \n1. For Addition \n2.For Subtraction \n3.For Multiplication \n4.For Division");
choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
Console.WriteLine(op1+op2);
break;
case 2:
Console.WriteLine(op1 - op2);
break;
case 3:
Console.WriteLine(op1*op2);
break;
case 4:
Console.WriteLine(op1/op2);
break;
default:
Console.WriteLine("Please enter valid Choice");
break;
}
end:
Console.WriteLine("Do you want to Continue(Y/N)?");
ch=Convert.ToChar(Console.Read());
if (ch == 'Y')
{
goto start;
}
else if (ch == 'N')
{
Console.ReadKey(true);
}
else
{
Console.WriteLine("Please Enter Valid Choice");
goto end;
}
}
But When I run the code it outputs as desired for the first time but when i select 'Y' it shows the error "exception of type 'System.FormatException' occurred in mscorlib.dll".Please Suggest me Some Correction
Replace ch=Convert.ToChar(Console.Read());
with ch = Console.ReadKey(true).KeyChar;
Though if I was to be a purist I'd have to say lose the labels and use a while loop.
I have tested your code.
After below line
ch=Convert.ToChar(Console.Read());
just add the following line because Console.Read() read single Character extra Enter is in buffer. so to clear the buffer after read() just add the below line.
Console.ReadLine();

Finding it difficult with the following code [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have written up to this place and am stuck I need help on how to terminate a program or continue .
What I mean is that when I ask the question would you like to withdraw today and if their response is NO then the program should terminate but if its YES it should continue.
What am I missing?
Please implement the aspect where by the program should terminate using the N for NO statement i didn't received the answer to that.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
Console.ReadLine();
}
}
}
You are on the right track. What you are missing is to take and evaluate the user input - this is the information returned by the Console.ReadLine method (as mentioned in the comments) like this:
line = Console.ReadLine();
Your code could look like this:
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
// save user input
var userInput = Console.ReadLine();
// evaluate if user wants to continue or not
if (userInput.ToLower() == "y")
{
// if yes, go further
Console.WriteLine("continue with other action...");
}
// else bye
Console.WriteLine("goodbye");
The line for the PIN already uses the user input! The same can be done with the question. If you want to stay in the loop until the user does not want to withdraw any more, than you need more than if-else. Take a look at the iteration statements like do and while.
A solution could look like this:
// user input = y or n
string choice;
// user pin
int pin = 0;
// state that indicates if the user wants to continue or not
bool continueLoop = false;
do
{
// greet user
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
// take input
choice = Console.ReadLine();
// check if user has entered valid input
if (choice.ToLower() == "y" || choice.ToLower() == "n")
{
// default decision is "user does not want to continue" = exit
continueLoop = false;
// user has choosen to continue
if (choice.ToLower() == "y")
{
// user wants to do something, so stay in the loop
continueLoop = true;
// ask for pin
Console.WriteLine("Enter your pin");
var pinAsText = Console.ReadLine();
// convert the pin to number: if (int.TryParse(pinAsText, out pin)) ...
if (pinAsText == "1234")
{
Console.WriteLine("PIN correct");
// continue with logic here, for example take amount
}
else
{
Console.WriteLine("PIN incorrect");
}
}
}
else
{
Console.WriteLine("Please enter Y or N");
continueLoop = true;
}
} while (continueLoop);
Console.WriteLine("goodbye");
Now the flow looks like this:
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> Y
Enter your pin
>> 3
PIN incorrect
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> Y
Enter your pin
>> 1234
PIN correct
welcome to HSPUIC bank would you like to make a withdraw today N or Y
>> N
goodbye
Certainly when your users have two different choice , you should use if in your program . Also you should save user's answer into a local variable to process it .
static void Main(string[] args)
{
int amount = 20000;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter your pin");
pin = int.Parse(Console.ReadLine());
Console.WriteLine("welcome to HSPUIC bank would you like to make a withdraw today N or Y");
char answer = char.Parse(Console.ReadLine());
if (answer == 'Y')
{
//Code that must be executed after choosing "yes" .
Console.ReadKey();
}
}
When you write nothing for "no" , your program will terminate .
Also you can use string instead of char :
string answer = Console.ReadLine();
if (answer == "Y")
{
//Code that must be executed after choosing "yes" .
Console.ReadKey();
}
By the way, there are a lot of possible errors in your code (e.g. enter a character instead of integer for variable ' pin ') that must be handled by try-catch.

Categories