User Input
The Crash Course
- Get input from the user with Console.ReadLine();
- Convert it to what you need using various Convert.To(_); commands.
- This tutorial also contains a complete sample that determines the surface area and volume of a cylinder, with dimensions from the user.
Introduction
In this short and simple tutorial, we'll look at two additional pieces of code that we'll need to create a simple program with some actual value.
We'll first learn how to get input from the user through the console window, then how to convert it to the right data types
Then we'll put these pieces and everything we've done so far together into a simple program that determines a cylinder's surface area and volume.
User Input from the Console
We can get input from the user by using a statement like the following:
string whatTheUserTyped = Console.ReadLine();
This is using another method (we'll discuss methods a lot more later) that reads in an entire line of text from the user (up until the press the <ENTER> key). What the user typed gets put in the variable on the left side, which in this case is called whatTheUserTyped. Remember that you could use any variable there. There's nothing special about this one.
Converting
For many things, though, simply grabbing the user's input and sticking it in a string variable doesn't get it into the right data type for what we need. For instance, what if we need the user to type in a number? When we put it into a string, we can't do addition or anything with it. We'll need to convert it to the right type of data before we can do anything with it. (Though sometimes, a string is the correct data type. For example, a person's name.)
So to convert to the right data type, we're going to use another method that converts any data type to another. (Well, we'll discuss the details of how this works later. That's the simplest way to put it, for now.)
To convert this to an integer, we'd do this:
int aNumber = Convert.ToInt32(whatTheUserTyped);
There's similar methods for each of the possible data types. For instance, ToInt16 is for the type short, ToBoolean is for the type bool, ToDouble is for the type double, and so on. One tricky one is that for the type float, you use ToSingle (as opposed to double—the float type is a "single" precision floating point value).
We'll see this pop up again in a second in the example program.
A Complete Sample Program
Cool. Now we've got a few more important pieces in place, and we can make a cool program that does something real. The program we're going to make is one that allows the user to type in two values, one for the radius of a cylinder and one for the height. We'll do some math (don't worry about the formulas, I'll provide them to you) to figure out the cylinder's volume and surface area. The program will then output the results to the user.
Now, the best way to do this would be for me to have you just do it on your own (don't you just love homework?). Struggling to put the pieces together on your own is the absolute best way to learn what parts you know and what parts you don't. Then, of course, you'd turn in your assignment, and we'd spend a few minutes looking it over together. But this is a tutorial, and it's not really going to be able to work out that way. After all, when you get done going through this tutorial, I'm probably going to be off watching an episode of Falling Skies, and I won't be around to discuss it with you.
So in an ideal world, you'd just go ahead and see if you can put the pieces together to do that program. In fact, I recommend that you go write the program now, then come back and compare it to what I've got. (Remember, though, that there is always more than one good way to write any given program. Just because yours and mine are different doesn't mean yours (or mine!) is necessarily wrong.)
Anyway, here's the code I have for this program.
// Print a greeting message. After all, why not? Console.WriteLine("Welcome to Cylinder Calculator 1.0!"); // Read in the cylinder's radius from the user Console.Write("Enter the cylinder's radius: "); string radiusAsAString = Console.ReadLine(); double radius = Convert.ToDouble(radiusAsAString); // Read in the cylinder's height from the user Console.Write("Enter the cylinder's height: "); string heightAsAString = Console.ReadLine(); double height = Convert.ToDouble(heightAsAString); double pi = 3.1415926536; // We'll learn a better way to do PI in the next tutorial // These are two standard formulas for volume and surface area of a cylinder. // You can find them on Wikipedia: http://en.wikipedia.org/wiki/Cylinder_(geometry) double volume = pi * radius * radius * height; double surfaceArea = 2 * pi * radius * (radius + height); // Now we output the results Console.WriteLine("The cylinder's volume is: " + volume + " cubic units."); Console.WriteLine("The cylinder's surface area is: " + surfaceArea + " square units.");
The first thing we add is a simple "welcome" message to the user.
// Print a greeting message. After all, why not? Console.WriteLine("Welcome to Cylinder Calculator 1.0!");
Again, this is basically identical to the hello world example we did earlier. No surprises here.
Next we prompt the user to enter the cylinder's radius and height, and turn them into the right data type using the things we learned in this tutorial:
// Read in the cylinder's radius from the user Console.Write("Enter the cylinder's radius: "); string radiusAsAString = Console.ReadLine(); double radius = Convert.ToDouble(radiusAsAString); // Read in the cylinder's height from the user Console.Write("Enter the cylinder's height: "); string heightAsAString = Console.ReadLine(); double height = Convert.ToDouble(heightAsAString);
The first line is like the Hello World example again, just simple output. We then read in the user's text and store it in a string object. The third line uses more stuff we learned in this tutorial and turns it into the correct data type (for this, we're going to use the double type). We repeat the process with the cylinder's height.
We then define the value of PI (as the comment indicates, more on this next tutorial) and use the math operations we learned last tutorial to calculate the volume and surface area of the cylinder.
double pi = 3.1415926536; // We'll learn a better way to do PI in the next tutorial // These are two standard formulas for volume and surface area of a cylinder. // You can find them on Wikipedia: http://en.wikipedia.org/wiki/Cylinder_(geometry) double volume = pi * radius * radius * height; double surfaceArea = 2 * pi * radius * (radius + height);
Finally, we output the results to the user, again using stuff from our first Hello World program:
// Now we output the results Console.WriteLine("The cylinder's volume is: " + volume + " cubic units."); Console.WriteLine("The cylinder's surface area is: " + surfaceArea + " square units.");
And there we have it! Our first useful C# program!
What's Next?
Now that we've learned a few last remaining pieces we need in order to create an actual, useful program, we're ready to kick it into high gear and make some cooler programs.
Our next stop is going to be to revisit C# math, this time going into a bit more detail. (Yes, I know. There's a lot of math in programming.) After that tutorial, we'll be ready to start to do logic, and make our computer be able to make choices about what it is doing!
Well, it was very different from the one in the tutorial, but I would like to share this:
Awesome! Thanks for sharing your code! I tweaked it just slightly to get the syntax highlighting.
I like that you're exploring it and trying out a different equation entirely. One question: shouldn't it be the area of the base that you're entering, rather than the entire surface area? The total surface area would include the area of the sides of the cylinder and top as well. Right?
Oh, I didn't look at this way. Yes, the surface would be composed by 3 areas, the base one, the middle circular area, and the upper one (same as the base area), so I think I confused up a bit :P
Hey, it's nice to see you! You are still active, and you answered me at the same day I have posted! I'm enjoying your tutorials very much, I was seeing some tutorials to make games in Unity, and I had trouble with some C# basics. I have studied a bit of C, but I struggle with new, public, private, SerializeField, methods, classes, coroutine, and some other things, so some people at Game Dev League discord said me to go back learn C# basics at your site. Now I understand why we need to use f after a number (to make it as a float), and the difference between c = ++a and c = a++. And I have many things to learn yet. I can assure you, your tutorial is one of the best tuts online, thank you for making it!
@Edit: One important thing I should have said, your commenting tutorial remembered that I need to comment my code! I have watched some video tutorials of how to make Unity games, and most of them don't comment their code (they are already explaining at the vid lol) so I have forgotten to do it, thanks for that! Also, before I would comment every line for the sake of doing it, so I would do good comments, but also really bad comments, now I'm only commenting when I think it's needed!
Just a tad bit curious. Is this assuming that all data fed into it is in Centimeters? Or some other unit? Also, I did some experimenting. Here is what I came up with:
Post preview:
Close preview