How to ask the user to input numbers only in integer? - c#

I want to ask the user to input a number including an if statement option were if he puts letters the last question will be asked again
I've tried this but seemingly it work only for strings
Console.Write("Write a number:");
int num = Convert.ToInt32(Console.ReadLine());
if (!int.TryParse(age, out num))
while(!int.TryParse(age, out num))
{
Console.WriteLine(...);
// ....
}

Let's extract method for this: we are going to ask user to input valid value until he or she provides it. So we have a loop:
private static int ReadInteger(string question) {
// Keep asking...
while (true) {
if (!string.IsNullOrWhiteSpace(question))
Console.WriteLine(question);
// ... until valid value provided
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine($"Sorry, not a valid integer value; please, try again.");
}
}
Then you can use it as
int age = ReadInteger("Please, input age");

I have a function that I'm using in my current project that might help you out, it just checks if the input string only contains numbers:
bool isDigitsOnly(string inputString)
{
foreach (char c in inputString)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
You might have to modify it a little bit to fit your needs, but it should work well enough

Related

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 to make user input int null value c#

I'm trying to make a program that takes a number and print it on screen but if the user press enter the code ask the user to enter the number again but instead it shows me a exception
Enter_No:
Console.WriteLine("enter number");
int? n = Convert.ToInt32(Console.ReadLine());
if (n == (int?)null)
{
goto Enter_No;
}
else
{
Console.WriteLine(n);
}
Use int.TryParse:
int? num = null;
while(!num.HasValue)
{
Console.WriteLine("Please enter an integer:");
num = int.TryParse(Console.ReadLine(), out int i) ? i : new int?();
}
Console.WriteLine("Entered integer: " + num.Value);
Tim's solution is wonderfully compact. Here's why your attempt failed.
From MSDN, Convert.ToInt32() throws a FormatException if:
value does not consist of an optional sign followed by a sequence of digits (0 through 9).
The preferred approach is int.TryParse(), as it returns false if it's unable to parse the integer rather than throwing an exception.
While the goto keyword is supported in C#, there are few or no situations (depending on who you ask) where it's the best option for flow control. Tim's while loop is an excellent approach.
First, don't use Go To:
Second: Inspect your data and use tryparse:
bool success = false;
do
{
Console.WriteLine("enter number");
var n = Console.ReadLine();
if (n == null)
{
// goto Enter_No;
}
else
{
int typedNum;
success = int.TryParse(n, out typedNum);
Console.WriteLine(typedNum);
}
} while (!success);

How do i check if an input matches a specific letter?

I can't figure out how to check whether the input is a specific letter. I know how to check if it's a specific int/double but when it's a string I don't know what to do.
Any help would be greatly appreciated. I'm just trying to make a basic 3 question quiz that checks whether the user answers with the correct letter (a, b or c) and then adds that to the current score.
class Program
{
static void Main()
{
var a1 = "a";
var a2 = "b";
var a3 = "c";
var qa = 0;
while (qa != 3)
{
if (qa == 0)
{
Console.Write("What is the answer to question 1? ");
var entry1 = Console.Read();
if()
{
}
}
else if (qa == 1)
{
Console.Write("What is the answer to question 2? ");
Console.ReadLine();
}
else if (qa == 2)
{
Console.Write("What is the answer to question 3? ");
Console.ReadLine();
}
}
}
}
For example operator == can't be applied to strings
this is not true. It can be applied:
if(entry.ToString() == a1)
The documentation for the == operator tells us:
For the string type, == compares the values of the strings
another possibility would be to use the String.Equals method
if(entry.ToString().Equals(a1))
EDIT:
Looking closer at your code I realized that you are using Console.Read
which
Reads the next character from the standard input stream.
That means that it returns a char (and only 1).
I guess you want the entire line that the user types in. So you should use ReadLine instead. It returns a string and allows you for a direct comparison
string entry1 = Console.ReadLine();
if(entry == a1)
when you use var for the declaration of types the compiler infers the type and the error becomes obvious at a later stage. you cannot use the == operator on string and char . Read() returns a char so that's why you were not able to compare it in the first place
Note that in "Question 1" you wrote Console.Read(), (not Console.ReadLine()) which returns a char, not a string. So "==" cannot be applied to entry1 and a1 since entry1 will be a char while a1 is a string.
If you compare compatible variables, everything should be fine
string input1;
var input2 = "";
var input3 = 0;
// assign some input values, then compare
// strings
if (input1 == "a") // ok
{ }
if (input2 == "a") // ok
{ }
if (input3 == "a") // not ok, comparing int to string
{ }
// numbers
if (input1 == 1) // not ok, comparing string to int
{ }
if (input3 == 1) // ok
{ }
If you want to, you could try matching the ASCII value of the character by using Console.Read();. This would eliminate the need to press enter. If you were trying to match to uppercase A:
int input = Console.Read();
if (input == (int)char.GetNumericValue(A))
{
Console.WriteLine("True");
Console.Read();
}
else
{
Console.WriteLine("False");
Console.Read();
}

Telephone number validation

I have this code to validate a phone number but it looks a bit awkward. I'm guessing theres a better way to go about this. How can I make this more efficient?
public static bool validTelephoneNo(string telNo)
{
bool condition = false;
while (condition == false)
{
Console.WriteLine("Enter a phone number.");
telNo = Console.ReadLine();
if (telNo.Length > 8)
{
if (telNo.StartsWith("+") == true)
{
char[] arr = telNo.ToCharArray();
for (int a = 1; a < telNo.Length; a++)
{
int temp;
try
{
temp = arr[a];
}
catch
{
break;
}
if (a == telNo.Length - 1)
{
condition = true;
}
}
}
}
}
return true;
}
Don't try and do this yourself, use a library where someone has already done the hard work for you, such as libphonenumber.
Example:
public static bool validTelephoneNo(string telNo)
{
PhoneNumber number;
try
{
number = PhoneNumberUtil.Instance.Parse(telNo, "US"); // Change to your default language, international numbers will still be recognised.
}
catch (NumberParseException e)
{
return false;
}
return number.IsValidNumber;
}
This library will handle parsing and formatting phone numbers from different countries. Not only will this ensure that the number is valid in the relevant country, it will also allow you to filter out premium numbers and "fake" numbers (such as 555 in the US).
Your goal can be easily achieved using regular expressions:
public static bool validTelephoneNo(string telNo)
{
return Regex.Match(telNo, #"^\+\d{1,7}$").Success;
}
This pattern is exactly as stated: consists of integers, is less than 8 digits in length and has a plus at the start, and also this pattern can be modified if conditions somehow more complex.
try
Console.WriteLine("Enter a phone number.");
bool isValid = new System.Text.RegularExpressions.Regex(#"^[+]\d{1,7}$").IsMatch(Console.ReadLine());
Where the regex checks whether there is only a single number (1 to 7 digits) with + in front of them read. The drawback, this way you cannot further processed, you might need to read the line from console to a new variable.

Convert String to int in C#

I am trying to write a simple program that asks the user to enter a number and then I will use that number to decide what the cost of the ticket will be for their given age. I am having trouble when trying to convert the string to int. Otherwise the program layout is fine. Any suggestions?
thanks
using System;
class ticketPrice
{
public static void Main(String[] args)
{
Console.WriteLine("Please Enter Your Age");
int input = Console.ReadLine();
if (input < 5)
{
Console.WriteLine("You are "+input+" and the admisson is FREE!");
}
else if (input > 4 & input < 18)
{
Console.WriteLine("You are "+input+" and the admission is $5");
}
else if (input > 17 & input < 56)
{
Console.WriteLine("You are "+input+" and the admission is $10");
}
else if (input > 55)
{
Console.WriteLine("You are "+input+" and the admission is $8");
}
}
}
Try the int.TryParse(...) method. It doesn't throw an exception.
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
Also, you should use && not & in your conditions. && is logical AND and & is bitwise AND.
For easy parsing of strings to integers (and other number types), use that number type's .TryParse(inputstring, yourintegervariable) method. This method will output a Boolean (True/False), letting you know whether the operation passed or failed. If the result is false, you can give an error message before going any further (don't have to worry about crashing your program).
Previous text concerning switch statements has been removed
In C#, you need to use the && operator for logical AND. & is not the same and may not work the way you believe it will.
I suggest to use the Int32.TryParse() method. Further I suggest to refactor your code - you can make it much cleaner (assuming this is not just example code). One solution is to use a key value pair list to map from age to admission.
using System;
using System.Collections.Generic;
using System.Linq;
static class TicketPrice
{
private static readonly IList<KeyValuePair<Int32, String>> AgeAdmissionMap =
new List<KeyValuePair<Int32, String>>
{
new KeyValuePair<Int32, String>(0, "FREE!"),
new KeyValuePair<Int32, String>(5, "$5."),
new KeyValuePair<Int32, String>(18, "$10."),
new KeyValuePair<Int32, String>(56, "$8.")
};
public static void Main(String[] args)
{
Console.WriteLine("Please Enter Your Age!");
UInt32 age;
while (!UInt32.TryParse(Console.ReadLine(), out age)) { }
String admission = TicketPrice.AgeAdmissionMap
.OrderByDescending(pair => pair.Key)
.First(pair => pair.Key <= age)
.Value;
Console.WriteLine(String.Format(
"You are {0} and the admission is {1}",
age,
admission));
}
}
I used an unsigned integer to prevent entering negative ages and put the input into a loop. This way the user can correct an invalid input.
int number = int.Parse(Console.ReadLine());
Be aware that this will throw an exception if they enter an invalid number.
The first thing you need to do is change your input variable to a string:
string input = Console.ReadLine();
Once you have that, there are several ways to convert it to an integer. See this answer for more info:
Better way to cast object to int

Categories

Resources