Step 3 - Read distance and time
Now you have a start, you keep progressing in the same way. Building up the code in small increments. For the next step, let’s read in the distance and time. This will need us to convert the data entered from text (what we read from the user) to numbers we can work with in the code.
The output we are aiming to create next is:
-
What new things do we have that changing now?
Both the distance and time may be different. These are numeric values, so they could either be
int
ordouble
values. Integers are whole numbers, doubles are real values.Add the code for these variables. I suggest placing this back up at the top, below the declaration of the
name
variable. -
Add the code to read these values in from the user.
Now, we have a problem - you cannot store the result of calling
ReadLine
into aint
or adouble
. How can we get this to work? There isn’t one method we can use to here, so we have to think about using what we have. If you look back at the terminal methods you will see there is aToInt32
and aToDouble
method. These convert strings to numeric values. We could read the text from the user into a string, and then convert that and store the result in our variables.- Add a
userInput
string variable. - Output appropriate messages with
Write
- Read input from the user, and store it in
userInput
- Convert
userInput
to the required type, and store the distance variable. - Repeat for the time variable
- Add a
-
Compile and run your program. Check the output matches what we are after.