dotNetD
dotNetD

Reputation: 31

Check if input has number and string to calculate in 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

Upvotes: 0

Views: 321

Answers (2)

Mert Sarıözkan
Mert Sarıözkan

Reputation: 16

    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);
    }

Upvotes: 0

Eiver
Eiver

Reputation: 2635

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.

Upvotes: 4

Related Questions