How to know what user entered in C# [duplicate] - c#

This question already has answers here:
C# testing to see if a string is an integer?
(10 answers)
Closed 6 years ago.
For Ex:
cw("enter anything");
//we dont know if user entered int or string or any other datatype so we would check as,
if(userEntered == int){}
if(userEntered==string){}
In other way: If user enters for example int value so we convert it and save it but if we dont know what user entered, how will we judge or detect?

For a console application taking in user input, assume its a string to begin with as string will be able to hold whatever the input is.
If needed, then you can parse it to another datatype such as ints or floats.

public class MainClass
{
public static void Main(string[] args)
{
String value = Console.ReadLine();
var a = new MainClass();
if a.IsNumeric(value){
//your logic with numeric
}
else
{
//your logic with string
}
}
public Boolean IsNumeric(String value){
try
var numericValue = Int64.Parse(value);
return true;
catch
return false;
}
In this case there is a separate function, which tries to convert it to number, if successful return true, otherwise false. With this you will avoid further code repetition to check if your value is numeric or not.

Once you have your string input, you can use TryParse to see if it is an int or a decimal (among other things)...
string userEntered = Console.ReadLine();
int tempInt;
decimal tempDec;
if(int.TryParse(userEntered, out tempInt))
MessageBox.Show("You entered an int: " + tempInt);
else if(decimal.TryParse(userEntered, out tempDec))
MessageBox.Show("You entered a decimal: " + tempDec);
else MessageBox.Show("You entered a string: " + userEntered);

There is no strict rule for that, User just enters a string value. It could be null or empty string or any other string, which might or might not be convertible to int or decimal or DateTime or any other datatype. So you just have to parse the input data and check whether its convertible to a datatype or not.

You can read user input through
console.readline
to check if it is a string or integer ,you can do something like this
by default user input is string
check the following code snippet
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
string input = Console.ReadLine();
Console.WriteLine(input);
int num2;
if (int.TryParse(input, out num2))
{
Console.WriteLine(num2);
}
}
}

Here is an example to check if user enters integer or string value:
Console.WriteLine("Enter value:");
string stringValue = Console.ReadLine();
int intValue;
if(int.TryParse(stringValue, out intValue))
{
// this is int! use intValue variable
}
else
{
// this is string! use stringValue variable
}

Console.WriteLine("enter someting");
string read = Console.ReadLine();
Console.Readline() read user input and will return a string
From here try to convert/parse it to other data type.

Related

C# My code is not doing math.. it is just sticking the numbers together

I am creating a friendly ai whose name is Phil ;), but I need it to be able to do math. I did try, and I also tried +=, but it wont work. For example, if I did 1+1, instead of 2, it would give me 11. Here is my code:
namespace Game
{
public static class Program
{
//commands
public static string enteredCommand;
public static string commanddomath = "doMath";
//Math command stuff
public static string MathOperation;
public static string FirstOperatorNumber;
public static string SecondOperatorNumber;
public static string FinalAwnser;
static void Main()
{
if (enteredCommand == "doMath")
{
Console.WriteLine("Ok");
Console.WriteLine("What Operation should I do?");
MathOperation = Console.ReadLine();
if (MathOperation == "+")
{
Console.WriteLine("Addition! Easy! What is the first number? ex. 6");
FirstOperatorNumber = Console.ReadLine();
Console.WriteLine("Ok, what do you want the second number to be? ex. 8");
SecondOperatorNumber = Console.ReadLine();
FinalAwnser = FirstOperatorNumber + SecondOperatorNumber;
Console.WriteLine("Ok! The awnser is..." + FinalAwnser);
}
}
else
{
Console.WriteLine("That is not a command");
}
Console.ReadKey();
}
}
}
Any help is appreciated!
Thanks
You are storing the user's input (FirstOperatorNumber and SecondOperatorNumber) as strings. The addition operator (+), when applied to two strings, performs an operation called concatenation: it adds the characters from each string to form another string.
But you want addition, which is the result of the addition operator being used on two integers. So you must store the user's input as an integer by replacing 'string' with 'int' in the variable declaration:
public static int FirstOperatorNumber;
public static int SecondOperatorNumber;
The input will still be a string, so you need to convert it as well, like this:
FirstOperatorNumber = Int32.Parse(Console.ReadLine());

I have a problem converting int to double

I'm a beginner programmer and at this moment i try to create primitive program for define variable types.
Below code and core of my problem.
namespace Moving
{
internal class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
if (int.TryParse(input, out int result1))
{
Console.WriteLine("type int");
}
if (double.TryParse(input, out double result2))
{
Console.WriteLine("type double");
}
else
{
Console.WriteLine("type String");
}
Console.ReadLine();
}
}
}
When i use string or double it works normally. But when i input int, works first if{} and second if{} too. For example i input 12. Program writes "type int" and "type double" because int may convert to double without efforts. I don't need it. Can i don't convert variable int to double? And i haven't a clue how i can explain to program to see difference between "string" and "char". What may do with it?
Because (mathematically) 1 = 1.0 is true, knowing this we derive that all integers are also valid decimal numbers, in programming terms we call them floating point numbers, and double is a floating point number type, meaning, it represents a floating point number, and as such can also represent integers*. So technically there's no problem, but it's not behaving how we want it to behave, so how do we fix this?
Easy, we use an else if statement instead of an if statement. The else if is only checked if the if (or else if) before it is false. Implementing it looks like this:
string input = Console.ReadLine();
if (int.TryParse(input, out int intResult))
{
Console.WriteLine("Integer");
}
else if (double.TryParse(input, out double doubleResult))
{
Console.WriteLine("Double");
}
else
{
Console.WriteLine("String");
}
*Okay, so technically double (and every floating point number type) can't represent every integer perfectly, because of how they're implemented in binary, but that's a whole other topic and too advanced for now, if you ever want to know more, check out Is floating point math broken?
Well, you can try else if instead of just if. Please, note, that every int can be parsed as double and every char can be treated as string:
if (int.TryParse(input, out int result1))
Console.WriteLine("type int");
else if (double.TryParse(input, out double result2))
Console.WriteLine("type double");
else if (input.Length == 1) // char is a string of Length == 1
Console.WriteLine("type char");
else
Console.WriteLine("type String");
In your statements, there are two different condition blocks. Therefore, you will get two outputs. If you only want to get one output. You should use one condition block: If, Else If, Else.
string input = Console.ReadLine();
if (int.TryParse(input, out int result1))
{
Console.WriteLine("type int");
}
else if (double.TryParse(input, out double result2))
{
Console.WriteLine("type double");
}
else
{
Console.WriteLine("type String");
}
Console.ReadLine();
You can use Convert class to Convert int to double
int n1 = 289;
double n2;
n2 = Convert.ToDouble(n1);

How can I handle an exception in C#? [duplicate]

This question already has answers here:
Parse v. TryParse
(8 answers)
Closed 5 years ago.
I'm trying to handle an exception to avoid my program crash if double.Parse(string) tries parsing invalid values (such as strings instead of numbers). Here's what I've got:
do
{
//asking customer the amount of shirts he would like to buy any shirts they want.
numbershirtString = Console.ReadLine(); // customer types in amount of shirts they want.
numbershirts = double.Parse(numbershirtString);
keepLooping = true;
if (numbershirts < 10)
{
Console.WriteLine("You would be buying " + numbershirts + " shirts");
keepLooping = false;
}
if (numbershirts > 10)
{
Console.WriteLine("You cannot order more than 10 shirts. Please try again.");
keepLooping = true;
}
} while (keepLooping);
I would appreciate your help. Thank you in advance!
Use double.TryParse() instead. It returns true of false depending on the outcome:
double val;
bool success = double.TryParse("red", out val);
if(success)
{
// val contains a parsed value
}
else
{
// could not parse
}
To handle an exception, in C# like similar in other languages, you can use the try..catch block.
Look at the simplest syntax:
try
{
//Try to run some code.
}
catch
{
//Do something if anything excepted.
}
If you're interested to retrieve which exception breaked the code:
try
{
//Try to run some code.
}
catch (Exception ex)
{
//Do something ex was thrown.
}
If you change the type of ex to something inheriting the base class Exception you'll handle only all the exception of that type:
try
{
//Try to run some code.
}
catch (StackOverflowException ex)
{
//Do something ex was thrown because you overflowed the stack.
}
But instead of talking about try..catch block which you can find out more about on Google, I suggest you to use the method double.TryParse(string, out double).
Its syntax is a little bit different than double.Parse, but effectively it does the same in a different way.
It returns true if your input is valid, else it returns false, whereas in the first parameter you have just to pass your string input and in the second one is required an output reference to the result variable:
double x = 0;
string number = "125.3";
if (double.TryParse(number, out x))
Console.WriteLine("Your number is " + x.ToString());
else
Console.WriteLine("Your input isn't valid");
Maybe this is a little advanced for you, but if you are feeling in a clever mood, you can define a class that handles the parsing of user input. That way you can keep that logic separated from your main program (see separation of concerns).
public class UserEntry
{
private readonly string _originalValue;
public UserEntry(string input)
{
_originalValue = input;
}
public bool IsInt
{
get
{
return int.TryParse(_originalValue, out var dummy);
}
}
public int ToInt()
{
return ToInt(default(int));
}
public int ToInt(int defaultValue)
{
int result;
bool ok = int.TryParse(_originalValue, out result);
return ok ? result : defaultValue;
}
public override string ToString()
{
return _originalValue;
}
static public implicit operator UserEntry(string input)
{
return new UserEntry(input);
}
static public implicit operator Int32(UserEntry input)
{
return input.ToInt();
}
}
If we use implicit conversion operators it makes things very simple. For example, all of these are now legal:
UserEntry entry = Console.ReadLine();
if (!entry.IsInt) continue;
if (entry < 10) return entry;
If we apply this to your example, it shortens your code a bit, and arguably makes it a bit clearer as well.
public class Program
{
private const int MaximumOrder = 10;
public static void Main()
{
var n = AskForNumberOfShirts();
Console.WriteLine("OK, I'll order {0} shirts.", n);
}
public static int AskForNumberOfShirts()
{
while (true)
{
Console.WriteLine("Enter the number of shirts to order:");
UserEntry entry = Console.ReadLine();
if (!entry.IsInt)
{
Console.WriteLine("You entered an invalid number.");
continue;
}
if (entry > MaximumOrder)
{
Console.WriteLine("{0} is too many! Please enter {1} or fewer.", entry, MaximumOrder);
continue;
}
return entry;
}
}
}
Notes:
I doubt you can order half a shirt, so I am using an int instead of a double to store the number of shirts.
I refactored the logic branches to use opportunistic return, a.ka. Guard Pattern. See this article for why I do this.
I extracted the constant value 10 to its own symbol, MaximumOrder. This should get you a couple points on the assignment.
Output:
Enter the number of shirts to order:
22
22 is too many! Please enter 10 or fewer.
Enter the number of shirts to order:
sdlfkj
You entered an invalid number.
Enter the number of shirts to order:
9
OK, I'll order 9 shirts.
Working example on DotNetFiddle

Converting Celcius to Fahrenheit - Double.TryParse

I have a successful clean code that does a conversion of Celcius to Fahrenheit using Double.Parse. However, I was curious on how it would look if I did a Double.TryParse but I can't seem to figure out how to complete the code. Once executed, I am able to present "Invalid Code", in my "if, else" but I still get this after my Invaild Output...
Please enter a value for conversion:
30x
Invalid code
The conversion from Celcius to Fahrenheit is: 32
using System;
using System.Text;
namespace CSharpBasics
{
class Program
{
public static double CelciusToFarenheit(string celciusTemperature)
{
//Converting string to a double for conversion
double celcius;
if (Double.TryParse(celciusTemperature, out celcius))
{
}
else
{
Console.WriteLine("Invalid code");
}
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter a value for conversion:");
var input = CelciusToFarenheit(Console.ReadLine());
Console.WriteLine("The conversion from Celcius to Fahrenheit is: " + input);
}
}
}
You should verify your input before the conversion to make sure you never display invalid result for an invalid input but return a message notifying the wrong input first. Something like this:
public static double CelciusToFarenheit(double celcius)
{
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter a value for conversion:");
var input = Console.ReadLine();
double celcius;
if (Double.TryParse(input, out celcius))
{
var result = CelciusToFarenheit(celcius);
Console.WriteLine("The conversion from Celcius to Fahrenheit is: " + result);
}
else
{
Console.WriteLine("Invalid code");
}
}
The method signature public static double CelciusToFarenheit(...) says that this method returns a value - and currently it does.
However, your program flow has to consider invalid input - and thus you need 2 information:
was the entered value a valid value
what's is the value
There are different methods to solve this issue, at least the following:
return a struct or object that holds both information
use the return value and indicate invalid results with exceptions
split the single method into 2 methods, one for checking validity and one for delivering the value.
Let's discuss the 3 options:
3) This might be looking nice, but when you look at Double.TryParse(), you'll likely introduce duplicate code. And when you look at the Main method, the abstraction level will not be the same.
2) Exceptions shall be used for exceptional cases. Wrong user input seems to be a rather usual thing. Not ideal for this case.
1) Sounds quite ok, except that the method might be responsible for 2 things: checking validity and calculating.
To implement that, you don't even need to write a new struct or class. You can simply use Nullable<double> or double?.
Since you're talking about clean code (potentially referring to R.C. Martin), I would start by looking at the main method. Basically I would say the code follows the IPO principle (input, processing, output). However, one line does 2 things:
var input = CelciusToFarenheit(Console.ReadLine());
Also, the variable name input is not so useful here, because it's not the input of the user, but the output after processing.
Proposal for that part:
public static void Main(string[] args)
{
var userInput = GetCelsiusInputFromUser();
var output = CelciusToFarenheit(userInput);
PrintOutput(output);
}
Also, the conversion method does not only convert, but print partial results as well:
Console.WriteLine("Invalid code");
I'd remove that piece and leave it to the output method to handle that case.
Full code:
using System;
namespace CSharpBasics
{
class Program
{
public static double? CelciusToFarenheit(string celciusTemperature)
{
//Converting string to a double for conversion
double celcius;
if (Double.TryParse(celciusTemperature, out celcius))
{
double fahrenheit = (celcius * 9 / 5) + 32;
return fahrenheit;
}
else
{
return null;
}
}
public static void Main(string[] args)
{
var userInput = GetCelsiusInputFromUser();
var output = CelciusToFarenheit(userInput);
PrintOutput(output);
}
private static void PrintOutput(double? output)
{
if (output == null)
{
Console.WriteLine("Invalid code");
}
else
{
Console.WriteLine("The conversion from Celcius to Fahrenheit is: " + output);
}
}
private static string GetCelsiusInputFromUser()
{
Console.WriteLine("Please enter a celsius value for conversion:");
var userInput = Console.ReadLine();
return userInput;
}
}
}
BTW: if you don't have a technical issue, https://codereview.stackexchange.com/ might be better suited for questions regarding clean code.

C#- Getting user input for Age.. but receiving error?

I am trying to make improve my programming and getting things drilled into my head so I'm just quickly developing an application that gets user's input and prints their name. But also gets their input for "Age verification".
I'm practicing IF & ELSE statements as well as nesting classes.
However my compiler is shooting me an error and I just cannot seem to figure it out. I'm trying to get the user to input his age, and then proceed with the IF & ELSE statement.
Compiler is shooting error that . ""Cannot implicitly convert type
string to int"
The only error in the program right now is the
myCharacter.age = Console.ReadLine();
using System;
namespace csharptut
{
class CharPrintName
{
static void Main()
{
Character myCharacter = new Character();
Console.WriteLine("Please enter your name to continue: ");
myCharacter.name = Console.ReadLine();
Console.WriteLine("Hello {0}!", myCharacter.name);
Console.WriteLine("Please enter your age for verification purposes: ");
myCharacter.age = Console.ReadLine();
if (myCharacter.age <= 17)
{
Console.WriteLine("I'm sorry {0}, you're too young to enter!",myCharacter.name);
}
else if (myCharacter.age >= 18)
{
Console.WriteLine("You can enter!");
}
}
}
class Character
{
public string name;
public int age;
}
}
As the error says you can't implicitly type a string to an int. You need to parse it into an int.
string input = Console.ReadLine();
int age;
if (int.TryParse(input, out age)
{
// input is an int
myCharacter.age = age;
}
else
{
// input is not an int
}
You are trying to assign a string value to an int with this line:
myCharacter.age = Console.ReadLine();
Try:
myCharacter.age = Int32.Parse(Console.ReadLine());
character.age expects an Int but ReadLine() returns a string, you need to look at using int.Parse or int.TryParse to avoid exceptions
e.g.
if (!int.TryParse(Console.ReadLine(),out myCharacter.age)) {
Console.WriteLine("You didn't enter a number!!!");
} else if (myCharacter.age <= 17) {
Console.WriteLine("I'm sorry {0}, you're too young to enter!",myCharacter.name);
} else {
Console.WriteLine("You can enter!");
}
This looks like a student project.
The input coming from the ReadLine() is always of type string. You're then comparing a string to 17 which isn't valid, as 17 is an int. Use TryParse versus parse to avoid throwing an exception at runtime.
string typedAge = Console.ReadLine();
int Age = 0;
if (!int.TryParse(typedAge, out Age))
Console.WriteLine("Invalid age");
if (Age <= 17)
Console.WriteLine("You're awfully young.");
OK. The problem here is that the age is defined as an int and Console.ReadLine() always returns a string so thus you have to convert the user input from string to integer in order to correctly store the age.
Something like this:
myCharacter.age = Int32.Parse(Console.ReadLine());
When you read input from the console, it returns it to you in the form of a string. In C#, which is a statically typed language, you cannot simply take one type and apply it to another type. You need to convert it somehow, there are several ways to do this.
The first way would be casting:
myCharacter.age = (int)Console.ReadLine();
This won't work because a string and an integer are two completely different types and you can't simply cast one to the other. Do some reading on casting types for more information.
The second way would be to convert it, again there are a couple of ways to do this:
myCharacter.age = Int32.Parse(Console.ReadLine());
This will work as long as you type in an actual number, in this case the Parse method reads the string and figures out what the appropriate integer is for you. However, if you type in "ABC" instead, you will get an exception because the Parse method doesn't recognize that as an integer. So the better way would be to:
string newAge = Console.ReadLine();
int theAge;
bool success = Int32.TryParse(newAge, out theAge);
if(!success)
Console.WriteLine("Hey! That's not a number!");
else
myCharacter.age = theAge;
In this case the TryParse method tries to parse it, and instead of throwing an exception it tells you it can't parse it (via the return value) and allows you to handle that directly (rather than thru try/catch).
That's a little verbose, but you said you're learning so I thought I'd give you some stuff to consider and read up on.

Categories

Resources