Check if input has number and string to calculate in C# - c#

I am really into the basics of programming and while writing a few lines of code to convert Celsius to Fahrenheit, which is pretty easy I started to wonder the following:
Can I make the program show me an answer depending if I wrote in the Console:
25C //to convert to F
or for example 100F // to convert to C
So far my knowledge goes to advanced "if" constructs and "for" cycles. Just started to study "do-while".
I am missing some knowledge how to properly search an input for number && specific char in order to give proper calculation.
I know that it seems a little complicated to make input :
25F // in one line instead of
25
F
but this will expand my knowledge and understanding.
I will try the latter now, should be easy, but can't find out how to do the former.
Thanks in advance!
Darin

In C# any string is actually a class, which contains useful methods for example:
string input = "25F";
if (input.EndsWith("F"))
{
// handle Fahrenheit
}
Then you can get rid of the last character like so:
string inputWithoutLastCharacter = input.Substring(0, input.Length - 1);
To convert a string to a number you can:
try
{
int number = int.Parse(inputWithoutLastCharacter);
}
catch (Exception ex)
{
Console.WriteLine("Could not convert your input to a number " + ex.ToString());
}
Try/catch is there to handle error cases where the input is not a valid number.
Also check out other methods of string. For example ToLower() to handle both "f" and "F".
Good luck.

String temp = Console.ReadLine();
char scale = temp[temp.Length-1];
if(temp.ToUpper().Contains("F")) {
int temperature = Int32.Parse(temp.Remove(temp.Length-1,1));
double celciusValueOfTemp = (temperature-32)/1.8;
Console.WriteLine(celciusValueOfTemp);
}
else if(temp.ToUpper().Contains("C")) {
int temperature = Int32.Parse(temp.Remove(temp.Length-1,1));
double fahrenheitValueOfTemp = temperature*1.8+32;
Console.WriteLine(fahrenheitValueOfTemp);
}

Related

False positive using string.length in if statement

I'm trying to format phone numbers. Perhaps my approach is not the best but it works with the exception of some unexpected behavior. I'm using string.length in an if statement to see if the phone number's length (stored as a string) is greater than 9. I've also tried >= 10 instead of > 9 with the same results. All works fine with 18001234567 or 7041234567. I get (800) 123-4567 or (704) 123-4567. But with 828464047 I get (82) 846-4047 rather than the number just being returned as is.
try
{
if (ANI.Length > 9)
{
char[] Number1 = { '1' };
ANI = ANI.TrimStart(Number1);
return String.Format("{0:(###) ###-####}", Convert.ToDouble(ANI));
}
else if (ANI == "")
{
return "Private";
}
else
{
return ANI;
}
}
catch (Exception ex)
{
return ex.Message;
}
Any ideas? Is there a better way to approach this?
Thanks.
If I change the code that formats the phone number to use substrings, things break, as expected.
return "(" + ANI.Substring(0, 3) + ") " + ANI.Substring(3, 3) + "-" + ANI.Substring(6, 4);
An exception is caught and "Index and length must refer to a location within the string. Parameter name: length" is returned.
I put it into a unit test method and it works. You're obviously getting an extra character added onto the string 828464047. You can debug and place a breakpoint at the IF statement and see what is actually in ANI.
A few things as well,
Don't name a variable something ambiguous like "ANI".
rename Number1 to something like "firstNumber"
A try/Catch is not needed for this statement, if you're getting an exception you're doing something that can be solved by better coding.
I can see ANI.TrimStart() in your code which leads me to suspect that you have some leading whitespace. You can probably best solve the problem by moving the trimming to outside the if.
It's pretty safe to assume that something as fundamental as String.Length works correctly. When it says your string is a certain length, your string really will be that length.
I'd check your inputs for whitespace or, perhaps you transcribed your input wrong here. The following tests pass against your code, copied and pasted:
[TestMethod, Owner("ebd"), TestCategory("Proven"), TestCategory("Unit")]
public void Ten_Digit_800_Number()
{
var myPad = new NumberFormatter();
Assert.AreEqual<string>("(800) 123-4567", myPad.FormatNumber("18001234567"));
}
[TestMethod, Owner("ebd"), TestCategory("Proven"), TestCategory("Unit")]
public void Ten_Digit_800_Number()
{
var myPad = new NumberFormatter();
Assert.AreEqual<string>("(800) 123-4567", myPad.FormatNumber("18001234567 "));
}
[TestMethod, Owner("ebd"), TestCategory("Proven"), TestCategory("Unit")]
public void TroubleString()
{
var myPad = new NumberFormatter();
Assert.AreEqual<string>("828464047", myPad.FormatNumber("828464047"));
}
The problem was stripping the leading '1' after having evaluated the length of the string. Stripping the '1' bef

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.

conversion from string to int while passing as a parameter in a method

I have a method that inputs an integer as a parameter in a class -
public string OddNumbers(int input)
and in my main program, I am trying to accept an integer from the user, through a textbox, and I am converting the input string to integer while passing the parameter -
string odd = od.OddNumbers(int.Parse((TextBox1.Text))).ToString();
and I am getting the following error:
"System.FormatException: Input string was not in a correct format."
I tried different methods of converting the integer to string, but results in the same error, for example:
string odd = od.OddNumbers(Convert.ToInt32(TextBox1.Text));
Any help in pointing out where I am going wrong?
What input are you trying to enter?
I would try a couple of things.
1) Run a trim on the input before passing it into the parse command. This will make sure there are no empty spaces at the end of the number.
2) If you are trying to accept a decimal, make sure you use double.
Do not nest functions, it makes code incredibly difficult do debug and maintain.
int Number;
if (int.TryParse(TextBox1.Text, out Number) == false)
{
// parsing error
Number = -1;
}
string odd = od.OddNumbers(Number);
The following should work assuming that the user enters a valid integer in the textbox:
int i = int.Parse(TextBox1.Text);
string odd = od.OddNumbers(i).ToString();
Another possible way to handle this is to use the TryParse method:
int i;
if (int.TryParse(TextBox1.Text, out i))
{
string odd = od.OddNumbers(i).ToString();
}
else
{
MessageBox.Show(TextBox1.Text + " is not a valid integer");
}
Once i put the method inside an click event, which finds out whether the input integer is odd or even, it gave me the desired result. thanks for all the inputs.

C# Converting a string containing a floating point to an integer

What is the best way to take a string which can be empty or contain "1.2" for example, and convert it to an integer? int.TryParse fails, of course, and I don't want to use float.TryParse and then convert to int.
Solution 1: Convert.ToDouble (culture-dependent)
You may using Convert.ToDouble. But, beware! The below solution will work only when the number separator in the current culture's setting is a period character.
var a = (int)Convert.ToDouble("1.2");
Solution 2: Convert.ToDouble (culture-independent)
It's preferable to use IFormatProvider and convert the number in an independent way from the current culture settings:
var a = (int)Convert.ToDouble("1.2", CultureInfo.InvariantCulture.NumberFormat);
Solution 3: Parse & Split
Another way to accomplish this task is to use Split on parsed string:
var a = int.Parse("1.2".Split('.')[0]);
Or:
var a = int.Parse("1.2".Split('.').First());
Notes
If you want to handle empty and null strings, write a method and add string.IsNullOrEmpty condition.
To get decimal separator for the current culture setting, you can use NumberFormatInfo.NumberDecimalSeparator property.
You should also keep eye on rounding to avoid traps.
Select casting, Parse, TryParse or Convert class wisely. Read more at:
How to: Convert a string to an int (C# Programming Guide)
How to: Determine Whether a String Represents a Numeric Value (C# Programming Guide)
I don't know what's wrong with parsing to a float and converting to an int. I doubt that any other way would be more efficient but here's an attempt:
//allows empty strings and floating point values
int ParseInt(string s, bool alwaysRoundDown = false)
{
//converts null/empty strings to zero
if (string.IsNullOrEmpty(s)) return 0;
if (!s.Contains(".")) return int.Parse(s);
string parts = s.Split(".");
int i = int.Parse(parts[0]);
if (alwaysRoundDown || parts.Length==1) return i;
int digitAfterPoint = int.Parse(parts[1][0]);
return (digitAfterPoint < 5) ? i : i+1;
}
In order to globalize the code you would need to replace "." with System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.
int a = (int)Math.Round(float.Parse("0.9"));
You need to round it first unless you want 0.9f being converted to 0 instead of 1.
Maybe you can try to delete everything after floating point using string functions and then convert to int. But seriously I don't think it's better than converting to float and then to int.
I think another way of doing it would be splitting the string into pieces taking the decimal (.) as the delimiter and then parsing for the integer. Of course, I am yet to ask you if the string might contain values like "37.56 miles in 32.65 seconds" type values.
Considering there will be only one value (string or number) in the string, I can think of something in the following line:
public int64 GetInt64(string input)
{
if (string.IsNullOrEmpty(input)) return 0;
// Split string on decimal (.)
// ... This will separate all the digits.
//
string[] words = input.Split('.');
return int.Parse(words[0]);
}
You can use the Visual Basic runtime Library to accomplish this from c#.
You need to add a reference to the assembly Microsoft.VisualBasic.dll to your solution.
Then the following code will do your conversion:
using VB = Microsoft.VisualBasic.CompilerServices;
class Program
{
static void Main(string[] args)
{
int i = VB.Conversions.ToInteger("1.2");
}
}
I had this same problem and ended up using a hybrid of Mark's and Dariusz':
if (num == "")
{
num = "0.00";
}
var num1 = (float)Convert.ToDouble(num);

C# dealing with invalid user input

Have a simple console app where user is asked for several values to input. Input is read via console.readline(). Ex
Name: Fred //string
Lastname: Ashcloud //string
Age: 28 //int
I would like to make sure that int and double types are entered and if the user enters garbage, lets him repeat the procedure.
Example, if the user enters "28 years old" where age expects int the app will crash. What is the best way to check for these inputs?
Right now I can only think of:
while (!Int32.TryParse(text, out number))
{
Console.WriteLine("Error write only numbers");
text = Console.ReadLine();
}
Is there any other way to do this? try catch statements if one wants to give a more detailed feedback to the user? How in that case?
For a console application, your code is perfectly fine.
However, you might want to abstract that into a reusable function so that you can read different numbers without repeating the code.
Also, you might want to provide some way for the user to cancel.
using System.Text.RegularExpressions;
int GetNumberFromString( string str_age )
{
Regex number = new Regex("[0-9][0-9]?");
Match n = number.Match(str_age);
if (n.Value != "")
return System.Convert.ToInt16(n.Value, 10);
else
return -1;
}
This will parse any data out besides the age or return -1 if no age is present.
this also assumes age 0-99.
Actually, your code is good. I would add negative number check, and perhaps huge number check too.
Regular Expressions are good.
Regex age = new Regex(#"^[0-9]*$");
while (!age.match(age_from_console)) {
Console.WriteLine("Age Invalid, try again ->");
}

Categories

Resources